<?php

namespace App\Mcp\Tools\GoogleAds;

use App\Agent\Choices;
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;
use Throwable;

#[Description('List enabled Google Ads conversion actions for the selected child account. Show the action names as selectable options and use the selected resource_name as the campaign conversion goal.')]
class ListConversionActions extends Tool
{
    public function __construct(
        private readonly GoogleAdsService $googleAds,
        private readonly Choices $choices,
    ) {}

    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->customer_id)) {
            return Response::error('Select a child Google Ads account first.');
        }

        try {
            $actions = $this->googleAds->conversionActionOptions($connection);
            $this->choices->offer(
                field: 'conversion_action_resource_name',
                question: 'Which conversion goal should this campaign use?',
                options: array_map(fn (array $action): array => [
                    'value' => $action['resource_name'],
                    'label' => $action['name'],
                    'hint' => $action['category'].' · '.$action['type'],
                    'sends' => 'Use conversion action '.$action['resource_name'].' as the conversion goal.',
                ], $actions),
            );
        } catch (Throwable $exception) {
            report($exception);

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

        return Response::json([
            'ok' => true,
            'conversion_actions' => $actions,
            'selection' => 'Ask the user to choose by name, then save the selected resource_name as conversion_action_resource_name.',
        ]);
    }
}
