<?php

namespace App\Mcp\Tools\TikTok;

use App\Campaigns\TikTokCampaignFlow;
use App\Models\TikTokConnection;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Http\Request as HttpRequest;
use Laravel\Ai\Models\Conversation;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;

#[Description('Validate the active TikTok campaign draft before showing its complete preview or creating it.')]
class ValidateTikTokCampaignDraft extends Tool
{
    public function __construct(
        private readonly HttpRequest $httpRequest,
        private readonly TikTokCampaignFlow $flow,
    ) {}

    public function schema(JsonSchema $schema): array
    {
        return ['conversation_id' => $schema->string()->description('TikTok conversation to validate')];
    }

    public function handle(Request $request): Response
    {
        $data = $request->validate(['conversation_id' => ['nullable', 'string', 'max:36']]);
        $user = $request->user();
        $conversationId = $data['conversation_id'] ?? $this->httpRequest->input('conversation');
        $conversation = is_string($conversationId)
            ? Conversation::query()
                ->whereKey($conversationId)
                ->where('chat_type', 'tiktok_ads')
                ->where('participant_type', $user?->getMorphClass())
                ->where('participant_id', $user?->getKey())
                ->first()
            : null;

        if ($user === null || $conversation === null) {
            return Response::error('TikTok chat conversation not found.');
        }

        $draft = json_decode((string) $conversation->tiktok_campaign_draft, true);
        $draft = is_array($draft) ? $draft : [];
        $connection = TikTokConnection::query()->where('user_id', $user->getAuthIdentifier())->first();
        $draft['advertiser_id'] = $connection?->advertiser_id;
        $draft['identity_id'] = $connection?->identity_id;
        $draft['tiktok_item_id'] = $connection?->tiktok_item_id;
        if (filled($connection?->identity_type)) {
            $draft['identity_mode'] = $connection->identity_type === 'BC_AUTH_TT' ? 'spark' : 'non_spark';
        }

        $next = $this->flow->next($draft);
        $alreadyValidated = $next === null && ($draft['validation_status'] ?? null) === 'passed';
        if (($next['field'] ?? null) !== 'validation_status' && ! $alreadyValidated) {
            $required = $next ? $next['stage_label'].' / '.$next['label'] : 'campaign validation';

            return Response::error('Complete '.$required.' before validating this TikTok draft.');
        }

        $draft['validation_status'] = 'passed';
        $conversation->update(['tiktok_campaign_draft' => json_encode($draft)]);

        $remoteSpark = strtolower((string) ($draft['creative_source'] ?? '')) === 'tiktok_post'
            && strtolower((string) ($draft['creative_format'] ?? '')) === 'single_video'
            && strtolower((string) ($draft['identity_mode'] ?? '')) === 'spark'
            && strtolower((string) ($connection?->identity_type ?? '')) === 'bc_auth_tt'
            && filled($connection?->tiktok_item_id);
        $remoteImage = strtolower((string) ($draft['creative_source'] ?? '')) === 'upload_image'
            && strtolower((string) ($draft['creative_format'] ?? '')) === 'single_image'
            && strtolower((string) ($draft['identity_mode'] ?? '')) === 'non_spark'
            && strtoupper((string) ($connection?->identity_type ?? '')) === 'CUSTOMIZED_USER'
            && (filled($draft['image_ids'] ?? null) || filled($draft['creative_asset_ids'] ?? null));
        $remoteSupported = strtolower((string) ($draft['campaign_type'] ?? '')) === 'manual'
            && strtolower((string) ($draft['promotion_type'] ?? '')) === 'website'
            && ($remoteSpark || $remoteImage);

        return Response::json([
            'ok' => true,
            'validation_status' => 'passed',
            'next' => $this->flow->next($draft),
            'remote_creation_supported' => $remoteSupported,
            'supported_delivery_options' => $remoteSupported ? ['draft', 'paused'] : ['draft'],
            'message' => $remoteSupported
                ? 'Draft validated. This configuration can be created on TikTok in paused state.'
                : 'Draft validated for local saving. This configuration is not supported by the current remote TikTok creator.',
        ]);
    }
}
