<?php

namespace Tests\Feature;

use App\Agent\Choices;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\CampaignImporter;
use App\Campaigns\PendingChanges;
use App\Campaigns\Publishing\MetaPublisher;
use App\Campaigns\Targeting\AudienceSizing;
use App\Campaigns\Targeting\MetaAudienceSelections;
use App\Models\Campaign;
use App\Models\User;
use App\Services\Meta\AdSetSpec;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request as ClientRequest;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use Mockery;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\TestWith;
use RuntimeException;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

class MetaAudienceSelectionTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

    public function test_publish_accepts_a_selected_pixel_on_a_later_account_page(): void
    {
        $campaign = $this->campaign();
        $campaign->update(['pixel_id' => '999']);
        config(['platforms.meta.token' => 'test-token', 'platforms.meta.mcp.enabled' => false]);
        Http::preventStrayRequests();
        Http::fake([
            'graph.facebook.com/*/act_123/adspixels*' => Http::sequence()
                ->push(['data' => [['id' => '1']], 'paging' => ['cursors' => ['after' => 'next'], 'next' => 'next-page']])
                ->push(['data' => [['id' => '999']]]),
            'graph.facebook.com/*/act_123?*' => Http::response(['id' => 'act_123']),
        ]);

        (new \ReflectionMethod(MetaPublisher::class, 'verifyPixel'))
            ->invoke(app(MetaPublisher::class), $campaign);

        Http::assertSentCount(3);
        Http::assertSent(fn (ClientRequest $request): bool => ($request['after'] ?? null) === 'next');
    }

    private function campaign(): Campaign
    {
        config(['platforms.guardrails.allowed_ad_accounts' => ['meta:act_123']]);
        $this->seedVerifiedCountries();
        $user = User::factory()->create();
        $this->actingAs($user);
        $campaign = Campaign::create([
            'user_id' => $user->getKey(), 'name' => 'Retargeting test',
            'platform' => 'meta', 'status' => 'draft',
            'ad_account_id' => 'act_123', 'locations' => ['countries' => ['US']],
            'special_ad_categories' => ['NONE'],
        ]);
        app(Workspace::class)->bindTo('meta-audience-conversation');
        app(Workspace::class)->focusOn($campaign);

        return $campaign;
    }

    private function fakeMeta(bool $available = true, string $audienceAccount = '123'): Meta
    {
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('deliveryEstimate')->andReturn([
            'data' => [['estimate_mau_lower_bound' => 50000, 'estimate_dau' => 1000]],
        ]);
        $meta->shouldReceive('pixels')->andReturn([['id' => '900', 'name' => 'Website pixel']]);
        $meta->shouldReceive('customAudiences')->andReturn([
            ['id' => '700', 'name' => 'Visitors', 'account_id' => $audienceAccount,
                'subtype' => 'WEBSITE', 'pixel_id' => '900',
                'operation_status' => ['code' => 200],
                'delivery_status' => ['code' => $available ? 200 : 300],
                'approximate_count_lower_bound' => 100,
                'approximate_count_upper_bound' => 200],
            ['id' => '701', 'name' => 'Uploaded customers', 'account_id' => '123',
                'subtype' => 'CUSTOM', 'pixel_id' => '',
                'operation_status' => ['code' => 200], 'delivery_status' => ['code' => 200]],
        ]);
        $this->app->instance(Meta::class, $meta);

        return $meta;
    }

    public function test_a_just_created_website_audience_is_attached_to_the_draft(): void
    {
        $campaign = $this->campaign();

        $set = app(MetaAudienceSelections::class)->recordCreated(
            $campaign,
            '701',
            'Retarget Purchase - 30 days',
            '900',
        );

        $this->assertSame(2, $set->revision);
        $this->assertSame('701', app(MetaAudienceSelections::class)->selected($campaign->fresh())[0]['id']);
        $this->assertSame('include', app(MetaAudienceSelections::class)->selected($campaign->fresh())[0]['operation']);
    }

    public function test_main_chat_chooses_only_a_verified_website_audience_and_rejects_stale_revision(): void
    {
        $campaign = $this->campaign();
        $this->fakeMeta();
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($candidate): bool => $candidate->name() === 'campaign__choose_audience_list');

        $review = json_decode((string) $tool->handle(new Request([])), true);
        $this->assertTrue($review['ok']);
        $this->assertTrue($review['lists'][0]['available']);
        $this->assertFalse($review['lists'][1]['available']);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $saved = json_decode((string) $tool->handle(new Request([
            'resource_name' => '700', 'operation' => 'include', 'expected_revision' => 0,
        ])), true);
        $this->assertTrue($saved['ok'], json_encode($saved));
        $this->assertSame('700', $saved['selected'][0]['id']);

        $stale = json_decode((string) $tool->handle(new Request([
            'resource_name' => '700', 'operation' => 'exclude', 'expected_revision' => 0,
        ])), true);
        $this->assertFalse($stale['ok']);
        $this->assertSame('include', app(MetaAudienceSelections::class)->selected($campaign->fresh())[0]['operation']);

        $snapshot = app(PendingChanges::class)->snapshot($campaign->fresh());
        $this->assertSame('700', $snapshot['meta_audiences'][0]['id']);
    }

    public function test_meta_audience_recheck_blocks_changed_provider_state_before_campaign_creation(): void
    {
        $campaign = $this->campaign();
        $this->fakeMeta();
        app(MetaAudienceSelections::class)->save($campaign, '700', 'exclude', 0);
        $this->fakeMeta(available: false);

        $publisher = app(MetaPublisher::class);
        $created = [];

        try {
            $publisher->create($campaign->fresh(), 'tester', $created);
            $this->fail('A stale website audience must block publication.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('unavailable or changed', $exception->getMessage());
        }

        $this->assertSame([], $created);
    }

    #[TestWith(['audience'])]
    #[TestWith(['pixel'])]
    public function test_publish_rejects_provider_changes_even_with_warm_discovery_in_the_same_request(string $changed): void
    {
        $campaign = $this->campaign();
        $campaign->update(['pixel_id' => '900']);
        config(['platforms.meta.token' => 'test-token', 'platforms.meta.mcp.enabled' => false]);
        Cache::flush();
        $pixels = [['id' => '900', 'name' => 'Website pixel']];
        $audiences = [
            ['id' => '700', 'name' => 'Visitors', 'account_id' => '123', 'subtype' => 'WEBSITE',
                'pixel_id' => '900', 'operation_status' => ['code' => 200], 'delivery_status' => ['code' => 200]],
        ];
        Http::preventStrayRequests();
        Http::fake([
            '*/act_123/adspixels*' => function () use (&$pixels) {
                return Http::response(['data' => $pixels]);
            },
            '*/act_123/customaudiences*' => function () use (&$audiences) {
                return Http::response(['data' => $audiences]);
            },
            '*/act_123*' => Http::response(['id' => 'act_123']),
        ]);
        app(MetaAudienceSelections::class)->save($campaign, '700', 'include', 0);

        if ($changed === 'pixel') {
            $pixels = [];
        } else {
            $audiences[0]['delivery_status']['code'] = 300;
        }

        $created = [];
        try {
            app(MetaPublisher::class)->create($campaign->fresh(), 'tester', $created);
            $this->fail('Cached discovery must not authorize a stale publish.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString(
                $changed === 'pixel' ? 'selected Meta pixel is unavailable' : 'unavailable or changed',
                $exception->getMessage(),
            );
        }

        $this->assertSame([], $created);
        Http::assertNotSent(fn (ClientRequest $request): bool => $request->method() !== 'GET');
    }

    public function test_audience_size_reports_require_fresh_pixel_and_audience_reads(): void
    {
        $campaign = $this->campaign();
        app(MetaAudienceSelections::class)->recordCreated($campaign, '700', 'Visitors', '900');
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('pixels')->once()->with('act_123', true)->andReturn([['id' => '900']]);
        $meta->shouldReceive('customAudiences')->once()->with('act_123', true)->andReturn([
            ['id' => '700', 'name' => 'Visitors', 'account_id' => '123', 'subtype' => 'WEBSITE',
                'pixel_id' => '900', 'operation_status' => ['code' => 200], 'delivery_status' => ['code' => 200],
                'approximate_count_lower_bound' => 150, 'approximate_count_upper_bound' => 250],
        ]);
        $this->app->instance(Meta::class, $meta);

        $sizes = app(MetaAudienceSelections::class)->listSizes($campaign->fresh());

        $this->assertSame('fresh', $sizes[0]['status']);
        $this->assertSame(150, $sizes[0]['lower_bound']);
        $this->assertSame(250, $sizes[0]['upper_bound']);
    }

    public function test_meta_ad_set_spec_sends_exact_included_and_excluded_audience_ids(): void
    {
        $spec = new AdSetSpec(
            adAccountId: 'act_123', campaignId: '456', name: 'Retargeting',
            budgetMinorUnits: 500, optimizationGoal: 'LINK_CLICKS', pageId: '111',
            targeting: [
                'countries' => ['US'],
                'meta_custom_audiences' => [['id' => '700']],
                'meta_excluded_custom_audiences' => [['id' => '702']],
                'meta_interests' => [['id' => '6001', 'name' => 'Physicians']],
            ],
        );

        $this->assertSame([['id' => '700']], $spec->targetingSpec()['custom_audiences']);
        $this->assertSame([['id' => '702']], $spec->targetingSpec()['excluded_custom_audiences']);
        $this->assertSame([['id' => '6001', 'name' => 'Physicians']], $spec->targetingSpec()['interests']);
    }

    public function test_threads_placement_uses_supported_position_and_required_instagram_feed(): void
    {
        $spec = new AdSetSpec(
            adAccountId: 'act_123', campaignId: '456', name: 'Threads placement',
            budgetMinorUnits: 500, optimizationGoal: 'LINK_CLICKS', pageId: '111',
            targeting: ['countries' => ['US'], 'placements' => ['threads']],
        );

        $targeting = $spec->targetingSpec();

        $this->assertSame(['threads', 'instagram'], $targeting['publisher_platforms']);
        $this->assertSame(['threads_stream'], $targeting['threads_positions']);
        $this->assertSame(['stream'], $targeting['instagram_positions']);
    }

    public function test_selected_interests_are_revalidated_before_targeting_is_published(): void
    {
        $campaign = $this->campaign();
        $campaign->update(['audience' => [
            'meta_audience_mode' => 'custom',
            'meta_interests' => [['id' => '6001', 'name' => 'Old interest label']],
        ]]);
        $meta = $this->fakeMeta();
        $meta->shouldReceive('validateTargetingInterests')->once()->with('act_123', ['6001'])->andReturn([
            ['id' => '6001', 'name' => 'Physicians', 'valid' => true],
        ]);

        $publisher = app(MetaPublisher::class);
        $targeting = (new \ReflectionMethod($publisher, 'targeting'))->invoke(
            $publisher,
            $campaign->fresh(),
            $campaign->fresh()->primaryAdSet,
        );

        $this->assertSame([['id' => '6001', 'name' => 'Physicians']], $targeting['meta_interests']);
    }

    public function test_a_too_narrow_meta_audience_is_refused_before_the_ad_set_is_created(): void
    {
        $campaign = $this->campaign();
        $campaign->update(['audience' => [
            'meta_audience_mode' => 'custom',
            'meta_interests' => [['id' => '6001', 'name' => 'Physicians']],
        ]]);
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('validateTargetingInterests')->once()->with('act_123', ['6001'])->andReturn([
            ['id' => '6001', 'name' => 'Physicians', 'valid' => true],
        ]);
        $meta->shouldReceive('deliveryEstimate')->once()->andThrow(new MetaException(
            'The configured audience is not valid: Broaden your audience to enable this ad to deliver. [OAuthException 100/2446395] on act_123/delivery_estimate',
        ));
        $this->app->instance(Meta::class, $meta);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('cannot deliver');
        (new \ReflectionMethod(app(MetaPublisher::class), 'targeting'))->invoke(
            app(MetaPublisher::class),
            $campaign->fresh(),
            $campaign->fresh()->primaryAdSet,
        );
    }

    public function test_interest_that_is_no_longer_valid_blocks_publish_targeting(): void
    {
        $campaign = $this->campaign();
        $campaign->update(['audience' => [
            'meta_audience_mode' => 'custom',
            'meta_interests' => [['id' => '6001', 'name' => 'Physicians']],
        ]]);
        $meta = $this->fakeMeta();
        $meta->shouldReceive('validateTargetingInterests')->once()->with('act_123', ['6001'])->andReturn([
            ['id' => '6001', 'name' => 'Physicians', 'valid' => false],
        ]);
        $publisher = app(MetaPublisher::class);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('no longer available');
        (new \ReflectionMethod($publisher, 'targeting'))->invoke(
            $publisher,
            $campaign->fresh(),
            $campaign->fresh()->primaryAdSet,
        );
    }

    public function test_duplicate_interest_ids_are_verified_and_returned_once(): void
    {
        $campaign = $this->campaign();
        $campaign->update(['audience' => ['meta_interests' => [
            ['id' => '6001', 'name' => 'Old label'],
            ['id' => '6001', 'name' => 'Repeated label'],
        ]]]);
        $meta = $this->fakeMeta();
        $meta->shouldReceive('validateTargetingInterests')->once()->with('act_123', ['6001'])->andReturn([
            ['id' => '6001', 'name' => 'Physicians', 'valid' => true],
        ]);

        $verified = (new \ReflectionMethod(app(MetaPublisher::class), 'verifiedInterests'))
            ->invoke(app(MetaPublisher::class), $campaign->fresh());

        $this->assertSame([['id' => '6001', 'name' => 'Physicians']], $verified);
    }

    #[DataProvider('malformedInterests')]
    public function test_malformed_saved_interests_fail_cleanly_before_provider_validation(mixed $interests): void
    {
        $campaign = $this->campaign();
        $campaign->update(['audience' => ['meta_interests' => $interests]]);
        $meta = $this->fakeMeta();
        $meta->shouldNotReceive('validateTargetingInterests');

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('Saved Meta interests are invalid');
        (new \ReflectionMethod(app(MetaPublisher::class), 'verifiedInterests'))
            ->invoke(app(MetaPublisher::class), $campaign->fresh());
    }

    public static function malformedInterests(): array
    {
        return [
            'scalar entry' => [['old format']],
            'missing id' => [[['name' => 'Interest']]],
            'invalid id' => [[['id' => 'not-an-id']]],
            'array id' => [[['id' => ['6001']]]],
            'scalar list' => ['6001'],
        ];
    }

    public function test_wrong_account_or_special_category_blocks_meta_website_audience(): void
    {
        $campaign = $this->campaign();
        $this->fakeMeta(audienceAccount: '999');
        $this->assertFalse(app(MetaAudienceSelections::class)->discover($campaign)[0]['available']);

        $this->fakeMeta();
        app(MetaAudienceSelections::class)->save($campaign, '700', 'include', 0);
        $campaign->update(['special_ad_categories' => ['HOUSING']]);
        $this->assertFalse(app(MetaAudienceSelections::class)->discover($campaign->fresh())[0]['available']);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('special ad category');
        app(MetaAudienceSelections::class)->verifiedForPublish($campaign->fresh());
    }

    public function test_meta_import_preserves_audience_ids_per_ad_set_and_refuses_to_flatten_them(): void
    {
        $campaign = $this->campaign();
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('campaignAccountId')->once()->andReturn('123');
        $meta->shouldReceive('campaign')->once()->andReturn([
            'id' => '456', 'name' => 'Imported Meta', 'objective' => 'OUTCOME_TRAFFIC',
            'special_ad_categories' => [],
        ]);
        $meta->shouldReceive('adSets')->once()->andReturn([[
            'id' => '88', 'targeting' => [
                'geo_locations' => ['countries' => ['US']],
                'custom_audiences' => [['id' => '700', 'name' => 'Visitors']],
                'excluded_custom_audiences' => [['id' => '702', 'name' => 'Buyers']],
            ],
        ]]);
        $meta->shouldReceive('adAccount')->once()->andReturn(['currency' => 'USD']);
        $meta->shouldNotReceive('createCampaign');
        $this->app->instance(Meta::class, $meta);

        $imported = app(CampaignImporter::class)->adopt('456', $campaign->user);
        $baseline = $imported->external_ids['meta_custom_audience_criteria'];

        $this->assertSame('88', $baseline[0]['adset_id']);
        $this->assertSame('700', $baseline[0]['custom_audiences'][0]['id']);
        $this->assertSame('702', $baseline[0]['excluded_custom_audiences'][0]['id']);
        $this->assertSame($baseline, $imported->published_state['meta_imported_custom_audience_criteria']);
        $html = view('partials.campaign-panel', [
            'campaign' => $imported, 'progress' => [], 'nextStep' => null,
            'blocking' => [], 'sources' => [], 'pending' => [], 'needsRebuild' => [],
            'campaigns' => collect([$imported]), 'assets' => collect(),
        ])->render();
        $this->assertStringContainsString('Imported Meta audiences', $html);
        $this->assertStringContainsString('exclude Meta audience ID 702 on ad set 88', $html);

        $imported->update(['external_campaign_id' => null, 'status' => 'draft']);
        $created = [];

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('original scope');
        app(MetaPublisher::class)->create($imported->fresh(), 'tester', $created);
    }

    public function test_meta_audience_sizing_reports_a_range_without_claiming_campaign_reach(): void
    {
        $campaign = $this->campaign();
        $this->fakeMeta();
        app(MetaAudienceSelections::class)->save($campaign, '700', 'include', 0);

        $estimate = app(AudienceSizing::class)->review($campaign->fresh(), refresh: true);

        $this->assertSame('fresh', $estimate['status']);
        $this->assertSame(100, $estimate['list_sizes'][0]['lower_bound']);
        $this->assertSame(200, $estimate['list_sizes'][0]['upper_bound']);
        $this->assertSame('unavailable', $estimate['campaign_reach_status']);

        $campaign->update(['special_ad_categories' => ['HOUSING']]);
        $unavailable = app(AudienceSizing::class)->review($campaign->fresh(), refresh: true);
        $this->assertSame('unavailable', $unavailable['list_sizes'][0]['status']);
        $this->assertNull($unavailable['list_sizes'][0]['lower_bound']);
    }

    public function test_selected_meta_interests_and_demographics_are_visible_in_campaign_review(): void
    {
        $campaign = $this->campaign();
        $campaign->update(['audience' => [
            'meta_audience_mode' => 'custom',
            'meta_interests' => [
                ['id' => '6001', 'name' => 'Vehicle insurance'],
                ['id' => '6002', 'name' => 'Automobiles'],
            ],
            'age_min' => 25,
            'age_max' => 44,
            'genders' => [2],
        ]]);

        $html = view('partials.campaign-panel', [
            'campaign' => $campaign->fresh(), 'progress' => [], 'nextStep' => null,
            'blocking' => [], 'sources' => [], 'pending' => [], 'needsRebuild' => [],
            'campaigns' => collect([$campaign]), 'assets' => collect(),
        ])->render();

        $this->assertStringContainsString('Audience interests', $html);
        $this->assertStringContainsString('Vehicle insurance', $html);
        $this->assertStringContainsString('Automobiles', $html);
        $this->assertStringContainsString('25–44', $html);
        $this->assertStringContainsString('Women', $html);
    }

    public function test_saved_schedule_is_visible_in_campaign_review(): void
    {
        $campaign = $this->campaign();
        $campaign->primaryAdSet->update([
            'starts_at' => now()->startOfDay(),
            'ends_at' => now()->addDays(14)->endOfDay(),
        ]);

        $html = view('partials.campaign-panel', [
            'campaign' => $campaign->fresh(), 'progress' => [], 'nextStep' => null,
            'blocking' => [], 'sources' => [], 'pending' => [], 'needsRebuild' => [],
            'campaigns' => collect([$campaign]), 'assets' => collect(),
        ])->render();

        $this->assertStringContainsString('Schedule', $html);
        $this->assertStringContainsString(now()->toDateString(), $html);
        $this->assertStringContainsString(now()->addDays(14)->toDateString(), $html);
    }

    public function test_campaign_review_shows_account_and_pixel_names_with_ids_and_currency(): void
    {
        $campaign = $this->campaign();
        $campaign->update([
            'currency' => 'USD',
            'pixel_id' => '900',
            'meta' => [
                'ad_account' => ['id' => 'act_123', 'name' => 'Direct Ads'],
                'pixel' => ['id' => '900', 'name' => 'Progressive Site Pixel'],
            ],
        ]);

        $html = view('partials.campaign-panel', [
            'campaign' => $campaign->fresh(), 'progress' => [], 'nextStep' => null,
            'blocking' => [], 'sources' => [], 'pending' => [], 'needsRebuild' => [],
            'campaigns' => collect([$campaign]), 'assets' => collect(),
        ])->render();

        $this->assertStringContainsString('Direct Ads', $html);
        $this->assertStringContainsString('act_123', $html);
        $this->assertStringContainsString('USD', $html);
        $this->assertStringContainsString('Progressive Site Pixel', $html);
        $this->assertStringContainsString('900', $html);
    }

    public function test_meta_audience_is_unavailable_until_the_special_category_is_declared(): void
    {
        $campaign = $this->campaign();
        $campaign->update(['special_ad_categories' => null]);
        $this->fakeMeta();

        $this->assertFalse(app(MetaAudienceSelections::class)->discover($campaign->fresh())[0]['available']);
    }
}
