<?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\Http;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * Detailed targeting on a live ad set is listed here. Creating a campaign is not.
 */
class DetailedTargetingCanBeListedForALiveEditTest 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,
        ]);

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

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

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

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

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('adset-1', $result['ad_set_id']);
        $this->assertSame([
            ['id' => '600', 'name' => 'Business administration', 'type' => 'interests'],
        ], $result['stored']);
        $this->assertSame([
            ['id' => '601', 'name' => 'Finance', 'type' => 'interests'],
        ], $result['matches']);
        $choice = collect(app(Choices::class)->all())->firstWhere('field', 'live_detailed_targeting');
        $this->assertTrue($choice['allow_other']);
        $this->assertSame('Search', $choice['other_label']);
        $this->assertSame('stock trading', $choice['other_placeholder']);
        $this->assertSame(
            ['Remove Business administration', 'Add Finance'],
            array_column($choice['options'], 'label'),
        );
        Http::assertNotSent(fn (HttpRequest $request): bool => str_contains($request->url(), 'targetingsearch'));
        Http::assertSent(fn (HttpRequest $request): bool => str_contains($request->url(), 'type=adinterestsuggestion'));
    }

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

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

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame([
            ['id' => '601', 'name' => 'Finance', 'type' => 'interests'],
        ], $result['matches']);
        $labels = array_column(
            collect(app(Choices::class)->all())->firstWhere('field', 'live_detailed_targeting')['options'],
            'label',
        );
        $this->assertSame(['Remove Business administration', 'Add Finance'], $labels);
        Http::assertNotSent(fn (HttpRequest $request): bool => $request->method() === 'POST');
    }

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

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

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame([
            ['id' => '700', 'name' => 'Stock market (investing)', 'type' => 'interests'],
            ['id' => '701', 'name' => 'Stock (investing)', 'type' => 'interests'],
            ['id' => '800', 'name' => 'Stock trading', 'type' => 'work_positions'],
        ], $result['matches']);
        $this->assertNotContains('Frequent travellers', array_column($result['matches'], 'name'));
    }

    public function test_creating_a_campaign_does_not_list_detailed_targeting(): void
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Draft',
            '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']);

        $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' => [
                        'flexible_spec' => [[
                            'interests' => [['id' => '600', 'name' => 'Business administration']],
                        ]],
                    ],
                ]);
            }

            if (str_ends_with($path, '/search')) {
                parse_str((string) parse_url($request->url(), PHP_URL_QUERY), $query);
                $type = (string) ($query['type'] ?? '');
                $term = (string) ($query['q'] ?? '');

                if ($type === 'adinterestsuggestion') {
                    return Http::response(['data' => [[
                        'id' => '601',
                        'name' => 'Finance',
                        'audience_size_lower_bound' => 1000,
                    ]]]);
                }

                if ($type === 'adinterest' && $term === 'finance') {
                    return Http::response(['data' => [[
                        'id' => '601',
                        'name' => 'Finance',
                        'audience_size_lower_bound' => 5000,
                    ]]]);
                }

                if ($type === 'adinterest' && $term === 'stock') {
                    return Http::response(['data' => [
                        ['id' => '701', 'name' => 'Stock (investing)', 'audience_size_lower_bound' => 1000],
                        ['id' => '700', 'name' => 'Stock market (investing)', 'audience_size_lower_bound' => 9000],
                        ['id' => '799', 'name' => 'Frequent travellers', 'audience_size_lower_bound' => 50],
                    ]]);
                }

                if ($type === 'adworkposition' && $term === 'stock') {
                    return Http::response(['data' => [[
                        'id' => '800',
                        'name' => 'Stock trading',
                        'audience_size_lower_bound' => 200,
                    ]]]);
                }

                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_detailed_targeting');

        $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);
    }
}
