<?php

namespace Tests\Feature;

use App\Agent\Answers;
use App\Agent\Choices;
use App\Agent\ToolRegistry;
use App\Agent\Tools\Campaign\CreateWebsiteAudience;
use App\Agent\Tools\Campaign\DuplicateCampaign;
use App\Agent\Workspace;
use App\Campaigns\CampaignApprovalBinding;
use App\Campaigns\Targeting\MetaAudienceSelections;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Campaign;
use App\Models\User;
use App\Services\Meta\GraphApi;
use App\Services\Meta\Meta;
use App\Services\Platforms\Support\CallLogger;
use App\Services\Platforms\Support\Guardrails;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use Mockery;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;

class WebsiteRetargetingAudienceTest extends TestCase
{
    use RefreshDatabase;

    private function campaign(string $specialCategory = 'NONE'): Campaign
    {
        config(['platforms.guardrails.allowed_ad_accounts' => ['meta:act_123']]);
        $user = User::factory()->create();
        $this->actingAs($user);
        $campaign = Campaign::create([
            'user_id' => $user->getKey(),
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'draft',
            'ad_account_id' => 'act_123',
            'objective' => 'OUTCOME_SALES',
            'locations' => ['countries' => ['US']],
            'special_ad_categories' => [$specialCategory],
        ]);
        app(TargetingSelections::class)->saveCampaignCountries($campaign, ['US']);
        app(Workspace::class)->bindTo('website-retargeting-conversation');
        app(Workspace::class)->ownedBy($user);
        app(Workspace::class)->focusOn($campaign);

        return $campaign;
    }

    private function tool(array $arguments = []): array
    {
        $result = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($tool) => $tool->name() === 'campaign__create_website_audience')
            ->handle(new Request($arguments));

        return json_decode((string) $result, true);
    }

    private function answer(string $field, mixed $value): array
    {
        return app(Answers::class)->applyAll([['field' => $field, 'value' => $value]]);
    }

    private function fakePixelMeta(): Meta
    {
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('pixels')->once()->with('act_123')->andReturn([
            ['id' => '900', 'name' => 'Winter Sale pixel'],
        ]);
        $meta->shouldReceive('pixels')->times(3)->with('act_123', true)->andReturn([
            ['id' => '900', 'name' => 'Winter Sale pixel'],
        ]);
        $meta->shouldReceive('pixelEvents')->times(3)->with('900')->andReturn([
            'Purchase' => 42,
            'AddToCart' => 160,
        ]);
        $meta->shouldReceive('createWebsiteAudience')->once()
            ->with('act_123', 'Winter Sale - Purchase (30 days)', '900', 'Purchase', 30)
            ->andReturn(['id' => '7001']);
        $this->app->instance(Meta::class, $meta);

        return $meta;
    }

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

        $this->assertTrue($this->tool()['ok']);
        $this->assertSame(['900'], array_column(
            collect(app(Choices::class)->all())->firstWhere('field', 'meta_retarget_pixel')['options'],
            'value',
        ));

        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $this->assertTrue($this->answer('meta_retarget_pixel', '900')[0]['applied']);
        $events = collect(app(Choices::class)->all())->firstWhere('field', 'meta_retarget_event')['options'];
        $this->assertSame(['Purchase', 'AddToCart'], array_column($events, 'value'));
        $this->assertStringContainsString('42 events', $events[0]['hint']);

        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $this->assertTrue($this->answer('meta_retarget_event', 'Purchase')[0]['applied']);
        $review = collect(app(Choices::class)->all())->firstWhere('field', 'meta_retarget_confirmation');
        $this->assertSame(['use_current', 'new_draft'], array_column($review['options'], 'value'));
        $this->assertSame('Purchase', $review['options'][0]['arguments']['event_name']);
        $this->assertSame(30, $review['options'][0]['arguments']['retention_days']);

        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $this->assertTrue($this->answer('meta_retarget_confirmation', 'use_current')[0]['applied']);
        $this->assertSame('7001', app(MetaAudienceSelections::class)->selected($campaign->fresh())[0]['id']);
        $this->assertSame('draft', $campaign->fresh()->status);
    }

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

        $this->tool();
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $this->answer('meta_retarget_pixel', '900');
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $this->answer('meta_retarget_event', 'Purchase');
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $applied = $this->answer('meta_retarget_confirmation', 'new_draft');

        $this->assertTrue($applied[0]['applied']);
        $draft = Campaign::query()->where('id', '!=', $campaign->getKey())->firstOrFail();
        $this->assertSame('draft', $draft->status);
        $this->assertNull($draft->external_campaign_id);
        $this->assertSame('7001', app(MetaAudienceSelections::class)->selected($draft)[0]['id']);
        $this->assertSame($campaign->getKey(), $campaign->fresh()->getKey());
    }

    public function test_audience_creation_is_refused_for_special_ad_categories(): void
    {
        $this->campaign('HOUSING');
        $meta = Mockery::mock(Meta::class);
        $meta->shouldNotReceive('pixels');
        $meta->shouldNotReceive('createWebsiteAudience');
        $this->app->instance(Meta::class, $meta);

        $result = $this->tool();

        $this->assertFalse($result['ok']);
    }

    public function test_failed_meta_creation_does_not_leave_a_retargeting_draft(): void
    {
        $campaign = $this->campaign();
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('pixels')->andReturn([['id' => '900', 'name' => 'Website pixel']]);
        $meta->shouldReceive('pixelEvents')->andReturn(['Purchase' => 42]);
        $meta->shouldReceive('createWebsiteAudience')->once()->andThrow(new \RuntimeException('Meta rejected the audience.'));
        $this->app->instance(Meta::class, $meta);

        $this->tool(['pixel_id' => '900', 'event_name' => 'Purchase']);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $result = $this->tool(['confirm_action' => 'new_draft']);

        $this->assertFalse($result['ok']);
        $this->assertSame(1, Campaign::query()->count());
        $this->assertTrue(app(Workspace::class)->focus()->is($campaign));
    }

    #[DataProvider('invalidConfirmations')]
    public function test_stale_or_changed_confirmation_cannot_create_an_audience(string $change): void
    {
        $campaign = $this->campaign();
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('pixels')->andReturn([['id' => '900', 'name' => 'Website pixel']]);
        $meta->shouldReceive('pixelEvents')->andReturn(['Purchase' => 42]);
        $meta->shouldNotReceive('createWebsiteAudience');
        $this->app->instance(Meta::class, $meta);

        $this->tool(['pixel_id' => '900', 'event_name' => 'Purchase']);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        if ($change === 'expired') {
            $this->travel(61)->minutes();
        } elseif ($change === 'campaign') {
            $campaign->update(['budget' => 25]);
        } elseif ($change === 'account') {
            $campaign->update(['ad_account_id' => 'act_999']);
        } else {
            $choices = app(Workspace::class)->pendingChoices();
            $choices[0]['options'][0]['arguments']['retention_days'] = 90;
            app(Workspace::class)->rememberChoices($choices);
        }

        $result = $this->tool(['confirm_action' => 'use_current']);

        $this->assertFalse($result['ok']);
        $this->assertSame(1, Campaign::query()->count());
        $this->assertSame([], app(MetaAudienceSelections::class)->selected($campaign->fresh()));
    }

    public static function invalidConfirmations(): array
    {
        return [['expired'], ['campaign'], ['account'], ['details']];
    }

    public function test_confirmation_cannot_be_replayed_to_create_another_audience(): void
    {
        $this->campaign();
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('pixels')->andReturn([['id' => '900', 'name' => 'Website pixel']]);
        $meta->shouldReceive('pixelEvents')->andReturn(['Purchase' => 42]);
        $meta->shouldReceive('createWebsiteAudience')->once()->andReturn(['id' => '7001']);
        $this->app->instance(Meta::class, $meta);

        $this->tool(['pixel_id' => '900', 'event_name' => 'Purchase']);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $this->assertTrue($this->tool(['confirm_action' => 'use_current'])['ok']);
        $this->assertFalse($this->tool(['confirm_action' => 'use_current'])['ok']);
    }

    #[DataProvider('eventHistoryPages')]
    public function test_complete_flow_stays_within_call_budget_across_fresh_requests(int $pages, int $expectedCalls): void
    {
        $this->campaign();
        config(['platforms.guardrails.paused' => false, 'platforms.guardrails.max_calls_per_hour' => 60]);
        Http::preventStrayRequests();
        Http::fake(function (\Illuminate\Http\Client\Request $request) use ($pages) {
            if (str_contains($request->url(), '/customaudiences')) {
                return Http::response(['id' => '7001']);
            }
            if (str_contains($request->url(), '/stats')) {
                $page = (int) ($request['after'] ?? 0) + 1;

                return Http::response([
                    'data' => [['data' => [['value' => 'Purchase', 'count' => 42]]]],
                    ...$page < $pages ? ['paging' => ['cursors' => ['after' => (string) $page]]] : [],
                ]);
            }
            if (str_contains($request->url(), '/adspixels') || str_contains($request->url(), '/owned_pixels')) {
                return Http::response(['data' => [['id' => '900', 'name' => 'Website pixel']]]);
            }

            return Http::response(['id' => 'act_123', 'business' => ['id' => '456']]);
        });

        foreach ([[], ['pixel_id' => '900'], ['pixel_id' => '900', 'event_name' => 'Purchase'], ['confirm_action' => 'use_current']] as $arguments) {
            $logger = new CallLogger(app(Guardrails::class));
            $meta = new Meta(new GraphApi('test-token', 'v25.0', $logger), null, $logger);
            $tool = new CreateWebsiteAudience(
                app(Workspace::class), app(Choices::class), $meta,
                app(MetaAudienceSelections::class), app(DuplicateCampaign::class), app(CampaignApprovalBinding::class),
            );
            $result = json_decode((string) $tool->handle(new Request($arguments)), true);

            $this->assertTrue($result['ok'], $result['error'] ?? 'The audience flow failed.');
            if (! isset($arguments['confirm_action'])) {
                app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
            }
        }

        Http::assertSentCount($expectedCalls);
        $this->assertLessThan(60, count(Http::recorded()));
    }

    public static function eventHistoryPages(): array
    {
        return ['single page' => [1, 16], 'pagination cap' => [4, 25]];
    }

    public function test_missing_provider_audience_id_does_not_create_a_draft(): void
    {
        $this->campaign();
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('pixels')->andReturn([['id' => '900', 'name' => 'Website pixel']]);
        $meta->shouldReceive('pixelEvents')->andReturn(['Purchase' => 42]);
        $meta->shouldReceive('createWebsiteAudience')->once()->andReturn(['success' => true]);
        $this->app->instance(Meta::class, $meta);

        $this->tool(['pixel_id' => '900', 'event_name' => 'Purchase']);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $result = $this->tool(['confirm_action' => 'new_draft']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('no audience ID', $result['error']);
        $this->assertSame(1, Campaign::query()->count());
    }

    public function test_audience_creation_requires_campaign_countries_before_reading_pixels(): void
    {
        $campaign = $this->campaign();
        app(TargetingSelections::class)->saveCampaignCountries($campaign, []);
        $meta = Mockery::mock(Meta::class);
        $meta->shouldNotReceive('pixels');
        $this->app->instance(Meta::class, $meta);

        $result = $this->tool();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('Choose the countries', $result['error']);
    }
}
