<?php

namespace App\Mcp\Tools\GoogleAds;

use App\Agent\Choices;
use App\Agent\Workspace;
use App\Models\GoogleAdsConnection;
use App\Services\GoogleAdsService;
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('List enabled child Google Ads accounts available to the authenticated user. Use this before creating a campaign when the user has multiple accounts.')]
class ListAccounts extends Tool
{
    public function __construct(
        private readonly GoogleAdsService $googleAds,
        private readonly Choices $choices,
        private readonly Workspace $workspace,
    ) {}

    public function schema(JsonSchema $schema): array
    {
        return [];
    }

    public function handle(Request $request): Response
    {
        $user = $request->user();
        if ($user === null) {
            return Response::error('Authentication is required.');
        }

        $connection = GoogleAdsConnection::query()->where('user_id', $user->getAuthIdentifier())->first();
        if ($connection === null || blank($connection->refresh_token)) {
            return Response::error('Connect a Google Ads account first.');
        }

        try {
            $accounts = collect($this->googleAds->childAccountOptions($connection))
                ->map(fn (array $account): array => [
                    'account_name' => $account['name'],
                    'customer_id' => $account['customer_id'],
                    'selected' => str_replace('-', '', (string) $connection->customer_id) === $account['customer_id'],
                    'select_value' => $account['customer_id'],
                ])
                ->all();
            $this->workspace->rememberGoogleAdsAccounts($accounts);
        } catch (\Throwable $exception) {
            report($exception);

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

        if ($accounts !== []) {
            $this->choices->offer(
                field: 'customer_id',
                question: 'Select the Google Ads child account to continue.',
                options: array_map(fn (array $account): array => [
                    'value' => $account['select_value'],
                    'label' => $account['account_name'].' ('.$account['customer_id'].')',
                    'sends' => 'Select Google Ads account '.$account['customer_id'],
                ], $accounts),
            );
        }

        return Response::json([
            'ok' => true,
            'accounts' => $accounts,
            'selection' => 'Choose an account by account_name, then call select_account with its select_value.',
        ]);
    }
}
