<?php

namespace App\Mcp\Tools\TikTok;

use App\Models\TikTokConnection;
use App\Services\TikTokService;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;
use Throwable;

#[Description('Create a TikTok web pixel for the selected advertiser when conversion tracking needs a pixel and none is configured. Use only after the user approves the pixel name.')]
class CreateTikTokPixel extends Tool
{
    public function __construct(private readonly TikTokService $tiktok) {}

    public function schema(JsonSchema $schema): array
    {
        return [
            'pixel_name' => $schema->string()->description('Name for the new TikTok web pixel')->required(),
        ];
    }

    public function handle(Request $request): Response
    {
        $data = $request->validate([
            'pixel_name' => ['required', 'string', 'max:255'],
        ]);
        $user = $request->user();
        $connection = $user === null
            ? null
            : TikTokConnection::query()->where('user_id', $user->getAuthIdentifier())->first();

        if ($connection === null || blank($connection->access_token) || blank($connection->advertiser_id)) {
            return Response::error('Connect TikTok Ads and select an advertiser before creating a pixel.');
        }

        try {
            $created = $this->tiktok->createPixel($connection, $data['pixel_name']);
        } catch (Throwable $exception) {
            report($exception);

            return Response::error($exception->getMessage());
        }

        $pixelId = data_get($created, 'pixel_id')
            ?? data_get($created, 'pixel.pixel_id')
            ?? data_get($created, 'data.pixel_id');
        if (! is_scalar($pixelId) || (string) $pixelId === '') {
            return Response::error('TikTok created the pixel but did not return a pixel ID.');
        }

        return Response::json([
            'ok' => true,
            'created' => true,
            'pixel_id' => (string) $pixelId,
            'pixel_name' => $data['pixel_name'],
            'next_step' => 'Use this pixel for conversion tracking and validate the TikTok campaign again.',
        ]);
    }
}
