<?php

namespace App\Mcp\Tools\GoogleAds;

use App\Agent\Workspace;
use App\Models\GoogleAdsConnection;
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('Select an enabled child Google Ads account for the authenticated user. Never select the manager account.')]
class SelectAccount extends Tool
{
    public function __construct(private readonly Workspace $workspace) {}

    public function schema(JsonSchema $schema): array
    {
        return [
            'customer_id' => $schema->string()->description('Child Google Ads customer ID')->required(),
        ];
    }

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

        $data = $request->validate(['customer_id' => ['required', 'string']]);
        $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.');
        }
        if (! in_array($data['customer_id'], $connection->available_customer_ids ?? [], true)
            || $data['customer_id'] === $connection->manager_customer_id) {
            return Response::error('Choose an enabled child account returned by Google.');
        }

        $account = collect($this->workspace->googleAdsAccounts())
            ->firstWhere('customer_id', $data['customer_id']);
        $accountName = (string) ($account['account_name'] ?? 'Google Ads account '.$data['customer_id']);

        $connection->customer_id = $data['customer_id'];
        $connection->save();
        $this->workspace->rememberGoogleAdsAccount([
            'customer_id' => $data['customer_id'],
            'account_name' => $accountName,
        ]);

        return Response::json([
            'ok' => true,
            'customer_id' => $connection->customer_id,
            'account_name' => $accountName,
            'message' => 'Selected '.$accountName.' ('.$connection->customer_id.').',
        ]);
    }
}
