<?php

namespace Limb_Chatbot\Includes\Services;

use Limb_Chatbot\Includes\Data_Objects\Chat;
use Limb_Chatbot\Includes\Data_Objects\Chat_Participant;
use Limb_Chatbot\Includes\Data_Objects\Chat_Meta;
use Limb_Chatbot\Includes\Factories\Chat_Service_Factory;
use Limb_Chatbot\Includes\Repositories\Chat_Repository;

/**
 * Handles lifecycle of preview chats per chatbot/user.
 *
 * @since 1.0.0
 */
class Preview_Chat_Lifecycle_Service {


	public function __construct() {
	}

	/**
	 * Delete all existing preview chats for the current user and chatbot,
	 * except the provided chat (which is the one being used now).
	 *
	 * @param Chat $chat Newly created (or current) chat used as context (chatbot + user).
	 *
	 * @return void
	 */
	public function delete_existing_preview_chats_for_context( Chat $chat ): void {
		$chatbot_id = $chat->get_chatbot_id();
		if ( empty( $chatbot_id ) ) {
			return;
		}

		$current_user = User_Manager::instance()->get_current_user();
		if ( ! $current_user ) {
			return;
		}

		$current_user_id = $current_user->get_id();

		// 1) Get chat IDs for this chatbot where current user participates as ROLE_USER.
		$participants = Chat_Participant::where(
			array(
				'user_id' => $current_user_id,
				'role'    => Chat_Participant::ROLE_USER,
			),
			-1,
			-1
		);
		if ( $participants->is_empty() ) {
			return;
		}

		$user_chat_ids = $participants->pluck('chat_id');
		if ( empty( $user_chat_ids ) ) {
			return;
		}

		// 2) Restrict to chats for the same chatbot_id.
		$chats = Chat::where(
			array(
				'id'         => $user_chat_ids,
				'chatbot_id' => $chatbot_id,
			),
			-1,
			-1
		);
		if ( $chats->is_empty() ) {
			return;
		}

		$eligible_chat_ids = array();
		foreach ( $chats->get() as $item ) {
			if ( ! $item instanceof Chat ) {
				continue;
			}
			$eligible_chat_ids[] = (int) $item->get_id();
		}

		if ( empty( $eligible_chat_ids ) ) {
			return;
		}

		// 3) Among those, filter only chats having meta 'preview'.
		$preview_metas = Chat_Meta::where(
			array(
				'chat_id'  => $eligible_chat_ids,
				'meta_key' => 'preview',
			),
			-1,
			-1
		);
		if ( $preview_metas->is_empty() ) {
			return;
		}

		$preview_chat_ids = array();
		foreach ( $preview_metas->get() as $meta ) {
			if ( ! $meta instanceof Chat_Meta ) {
				continue;
			}
			$meta_chat_id = (int) $meta->get_chat_id();
			if ( $meta_chat_id && $meta_chat_id !== $chat->get_id() ) {
				$preview_chat_ids[] = $meta_chat_id;
			}
		}

		if ( empty( $preview_chat_ids ) ) {
			return;
		}

		$preview_chat_ids = array_values( array_unique( $preview_chat_ids ) );

		// 4) Delete only those old preview chats for this user + chatbot.
		foreach ( $preview_chat_ids as $chat_id ) {
			$old_chat = Chat::find( $chat_id );
			if ( ! $old_chat instanceof Chat ) {
				continue;
			}
			$service = ( new Chat_Service_Factory() )->make( $old_chat->get_chatbot() );
			$service->delete( $old_chat );
		}
	}
}

