<?php

namespace Tests\Feature;

use App\Agent\Choices;
use App\Agent\NamespacedTool;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request as HttpRequest;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * A live location change lists Meta's matches. Creating a campaign does not.
 */
class LiveLocationCanBeListedForAnEditTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

    protected function setUp(): void
    {
        parent::setUp();

        config([
            'platforms.meta.token' => 'test-token',
            'platforms.meta.mcp.enabled' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['meta:*'],
            'platforms.guardrails.paused' => false,
        ]);

        Cache::flush();

        $this->user = User::factory()->create();
        $this->actingAs($this->user);

        app(Workspace::class)->bindTo('conv-location');
        app(Workspace::class)->ownedBy($this->user);
    }

    public function test_a_state_search_offers_the_name_and_the_region_key(): void
    {
        $this->campaign();
        $this->fakeMeta();

        $result = $this->list(['ad_set' => 'Winter ad set', 'query' => 'New York', 'kind' => 'region']);

        $this->assertTrue($result['ok']);
        $this->assertSame('US', $result['country_code']);
        $this->assertSame([[
            'kind' => 'region',
            'key' => '3875',
            'name' => 'New York',
            'label' => 'New York, US',
        ]], $result['matches']);

        $choice = app(Choices::class)->all()[0];
        $this->assertSame('live_location', $choice['field']);
        $this->assertTrue($choice['multiple']);
        $this->assertSame('New York, US · region', $choice['options'][0]['label']);
        $this->assertSame('ID 3875', $choice['options'][0]['hint']);
        $this->assertStringContainsString('edit_entity once', $choice['options'][0]['sends']);
        $this->assertStringContainsString('every included place', $choice['options'][0]['sends']);
        $this->assertStringContainsString('{"key":"3875"}', $choice['options'][0]['sends']);
        $this->assertStringContainsString('Do not include countries', $choice['options'][0]['sends']);
        Http::assertNotSent(fn (HttpRequest $request): bool => $request->method() === 'POST');
    }

    public function test_a_place_name_offers_the_state_and_the_city(): void
    {
        $this->campaign();
        $this->fakeMeta();

        $result = $this->list(['ad_set' => 'adset-1', 'query' => 'New York']);

        $this->assertTrue($result['ok']);
        $this->assertSame(['3875', '2490299'], array_column($result['matches'], 'key'));
        $this->assertSame(['region', 'city'], array_column($result['matches'], 'kind'));

        $choice = app(Choices::class)->all()[0];
        $this->assertTrue($choice['multiple']);
        $options = $choice['options'];
        $this->assertSame('New York, US · region', $options[0]['label']);
        $this->assertSame('New York, New York, US · city', $options[1]['label']);
        $this->assertStringContainsString('every included place', $options[0]['sends']);
        $this->assertStringContainsString('{"key":"2490299"}', $options[1]['sends']);
    }

    public function test_a_later_search_keeps_a_place_already_chosen(): void
    {
        $this->campaign();
        $this->fakeMeta();

        $result = $this->list([
            'ad_set' => 'Winter ad set',
            'query' => 'New York',
            'kind' => 'region',
            'keep' => [['kind' => 'region', 'key' => '4081', 'name' => 'California']],
        ]);

        $this->assertTrue($result['ok']);
        $this->assertSame('4081', $result['kept'][0]['key']);
        $this->assertSame('3875', $result['matches'][0]['key']);

        $labels = array_column(app(Choices::class)->all()[0]['options'], 'label');
        $this->assertSame(['California · region', 'New York, US · region'], $labels);
        Http::assertNotSent(fn (HttpRequest $request): bool => $request->method() === 'POST');
    }

    public function test_no_query_lists_every_state_for_multiple_selection(): void
    {
        $this->campaign();
        $this->fakeMeta();

        $result = $this->list(['ad_set' => 'Winter ad set']);

        $this->assertTrue($result['ok']);
        $this->assertSame(['Alabama', 'New York', 'Texas'], array_column($result['matches'], 'name'));
        $this->assertSame(['3843', '3875', '3886'], array_column($result['matches'], 'key'));

        $choice = app(Choices::class)->all()[0];
        $this->assertTrue($choice['multiple']);
        $this->assertFalse($choice['allow_other']);
        $this->assertSame('Which states should this ad set target?', $choice['question']);
        $this->assertSame('Alabama, US · region', $choice['options'][0]['label']);
        $this->assertSame('ID 3843', $choice['options'][0]['hint']);
        $this->assertStringContainsString('every included place', $choice['options'][0]['sends']);
        $this->assertStringContainsString('{"key":"3886"}', $choice['options'][2]['sends']);
        Http::assertNotSent(fn (HttpRequest $request): bool => $request->method() === 'POST');
    }

    public function test_a_draft_campaign_does_not_list_locations(): void
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'draft',
            'objective' => 'OUTCOME_TRAFFIC',
            'ad_account_id' => 'act_111',
            'currency' => 'USD',
            'budget' => 25,
            'budget_mode' => 'daily',
        ]);

        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign);
        Http::fake();

        $result = $this->list(['ad_set' => 'Winter ad set', 'query' => 'New York']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('already live', $result['error']);
        $this->assertSame([], app(Choices::class)->all());
        Http::assertNothingSent();
    }

    private function campaign(): void
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'published',
            'objective' => 'OUTCOME_TRAFFIC',
            'ad_account_id' => 'act_111',
            'currency' => 'USD',
            'budget' => 25,
            'budget_mode' => 'daily',
            'external_campaign_id' => '120252047635070626',
        ]);

        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign);
    }

    private function fakeMeta(): void
    {
        Http::fake(function (HttpRequest $request) {
            $path = parse_url($request->url(), PHP_URL_PATH) ?? '';

            if (str_ends_with($path, '/adsets')) {
                return Http::response(['data' => [['id' => 'adset-1', 'name' => 'Winter ad set']]]);
            }

            if (str_ends_with($path, '/adset-1')) {
                return Http::response([
                    'id' => 'adset-1',
                    'targeting' => [
                        'geo_locations' => ['countries' => ['US']],
                    ],
                ]);
            }

            if (str_ends_with($path, '/search')) {
                parse_str((string) parse_url($request->url(), PHP_URL_QUERY), $query);
                $types = json_decode((string) ($query['location_types'] ?? ''), true);

                if ($types === ['region'] && ($query['q'] ?? '') === 'al') {
                    return Http::response(['data' => [
                        ['key' => '3843', 'name' => 'Alabama', 'type' => 'region', 'country_code' => 'US'],
                        ['key' => '3875', 'name' => 'New York', 'type' => 'region', 'country_code' => 'US'],
                        ['key' => '99', 'name' => 'New York', 'type' => 'region', 'country_code' => 'GB'],
                    ]]);
                }

                if ($types === ['region'] && ($query['q'] ?? '') === 'st') {
                    return Http::response(['data' => [
                        ['key' => '3886', 'name' => 'Texas', 'type' => 'region', 'country_code' => 'US'],
                        ['key' => '3875', 'name' => 'New York', 'type' => 'region', 'country_code' => 'US'],
                    ]]);
                }

                if ($types === ['region']) {
                    return Http::response(['data' => [
                        ['key' => '3875', 'name' => 'New York', 'type' => 'region', 'country_code' => 'US'],
                        ['key' => '4081', 'name' => 'California', 'type' => 'city', 'country_code' => 'US'],
                        ['key' => '99', 'name' => 'New York', 'type' => 'region', 'country_code' => 'GB'],
                    ]]);
                }

                if ($types === ['city']) {
                    return Http::response(['data' => [[
                        'key' => '2490299',
                        'name' => 'New York',
                        'type' => 'city',
                        'region' => 'New York',
                        'country_code' => 'US',
                    ]]]);
                }

                return Http::response(['data' => []]);
            }

            return Http::response(['success' => true]);
        });
    }

    private function tool(): NamespacedTool
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($candidate): bool => $candidate->name() === 'campaign__list_live_locations');

        $this->assertNotNull($tool);

        return $tool;
    }

    /** @param  array<string, mixed>  $arguments */
    private function list(array $arguments): array
    {
        return json_decode((string) $this->tool()->handle(new Request($arguments)), true);
    }
}
