<?php

namespace App\Mcp\Tools\TikTok;

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

#[Description('Persist one TikTok identity previously returned by list-identities.')]
class SelectIdentity extends Tool
{
    public function schema(JsonSchema $schema): array
    {
        return [
            'identity_id' => $schema->string()->required(),
            'identity_type' => $schema->string()->description('Optional when identity_id matches an authorized identity.'),
        ];
    }

    public function handle(Request $request): Response
    {
        $data = $request->validate([
            'identity_id' => ['required', 'string'],
            'identity_type' => ['nullable', 'string'],
        ]);
        $connection = TikTokConnection::query()->where('user_id', $request->user()?->getAuthIdentifier())->first();
        if ($connection === null || ! is_array($connection->identities)) {
            return Response::error('List TikTok identities before selecting one.');
        }

        $identity = collect($connection->identities)->first(fn (array $identity): bool => $identity['identity_id'] === $data['identity_id']
            && (blank($data['identity_type']) || $identity['identity_type'] === $data['identity_type'])
        );
        if (! is_array($identity)) {
            return Response::error('Choose a TikTok identity returned for the selected advertiser.');
        }

        $connection->forceFill([
            'identity_id' => $identity['identity_id'],
            'identity_authorized_bc_id' => $identity['identity_authorized_bc_id'] ?? null,
            'identity_type' => $identity['identity_type'],
            'identity_name' => $identity['identity_name'],
            'tiktok_posts' => null,
            'tiktok_item_id' => null,
        ])->save();

        return Response::json(['ok' => true, 'selected_identity' => $identity]);
    }
}
