<?php

namespace Tests\Feature;

use App\Agent\Choices;
use App\Agent\NamespacedTool;
use App\Agent\Tools\Campaign\EditGoogleAudienceTargeting;
use App\Agent\Tools\Campaign\SearchGoogleAudienceSegments;
use App\Agent\Workspace;
use App\Campaigns\Manager\Canonical;
use App\Models\Campaign;
use App\Models\CampaignChange;
use App\Models\User;
use App\Services\GoogleAdsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Tools\Request;
use Mockery;
use Tests\TestCase;

class GoogleChatAudienceTargetingTest extends TestCase
{
    use RefreshDatabase;

    private const string SEGMENT = 'customers/1234567890/userInterests/555';

    private const string OTHER_SEGMENT = 'customers/1234567890/userInterests/556';

    private array $criteria;

    private array $restrictions;

    private bool $segmentAvailable = true;

    private string $segmentName = 'Cardio Equipment';

    private bool $ignoreUpdate = false;

    protected function setUp(): void
    {
        parent::setUp();
        config([
            'platforms.guardrails.allowed_ad_accounts' => ['google:*'],
            'platforms.guardrails.paused' => false,
            'platforms.guardrails.dry_run' => false,
            'platforms.guardrails.change_cooldown_seconds' => 0,
            'platforms.guardrails.max_changes_per_day' => 100,
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '1234567890',
        ]);
        $user = User::factory()->create();
        $this->actingAs($user);
        $workspace = app(Workspace::class);
        $workspace->bindTo('google-audience-targeting');
        $workspace->ownedBy($user);
        $campaign = Campaign::create([
            'user_id' => $user->id, 'name' => 'Display', 'platform' => 'google',
            'status' => 'published', 'ad_account_id' => '1234567890', 'external_campaign_id' => '101',
        ]);
        $workspace->produced($campaign);
        $workspace->focusOn($campaign);
        $this->restrictions = [
            ['targetingDimension' => 'AUDIENCE', 'bidOnly' => true],
            ['targetingDimension' => 'PLACEMENT', 'bidOnly' => false],
        ];
        $this->criteria = [[
            'resourceName' => 'customers/1234567890/adGroupCriteria/201~1', 'adGroup' => 'customers/1234567890/adGroups/201',
            'type' => 'GENDER', 'status' => 'ENABLED', 'negative' => true, 'gender' => ['type' => 'FEMALE'],
        ]];
        $google = Mockery::mock(GoogleAdsService::class)->makePartial();
        $google->shouldReceive('readCampaignStructure')->andReturnUsing(fn (): array => [
            'channel_type' => 'DISPLAY',
            'ad_groups' => [['id' => '201', 'type' => 'DISPLAY_STANDARD', 'target_restrictions' => $this->restrictions]],
        ]);
        $google->shouldReceive('readManagerAudiences')->andReturnUsing(fn (): array => ['201' => $this->criteria]);
        $google->shouldReceive('userInterests')->andReturnUsing(function ($connection, string $channel, ?string $resourceName = null, ?string $nameSearch = null): array {
            $segments = $this->segmentAvailable ? [
                ['resource_name' => self::SEGMENT, 'name' => $this->segmentName, 'taxonomy_type' => 'IN_MARKET'],
                ['resource_name' => self::OTHER_SEGMENT, 'name' => 'Fitness Services', 'taxonomy_type' => 'AFFINITY'],
            ] : [];

            return array_values(array_filter($segments, fn (array $segment): bool => $resourceName !== null
                ? $segment['resource_name'] === $resourceName
                : stripos($segment['name'], (string) $nameSearch) !== false));
        });
        $google->shouldReceive('updateAdGroup')->andReturnUsing(function ($connection, string $id, array $fields): void {
            $this->assertSame('201', $id);
            if (! $this->ignoreUpdate) {
                $this->restrictions = $fields['target_restrictions'];
            }
        });
        $google->shouldReceive('updateManagerAudiences')->andReturnUsing(function ($connection, string $id, array $before, array $after): void {
            $this->assertSame('201', $id);
            if ($this->ignoreUpdate) {
                return;
            }
            $next = [];
            foreach ($after as $selection) {
                $matched = null;
                foreach ($this->criteria as $row) {
                    $content = array_diff_key($row, array_flip(['resourceName', 'adGroup', 'status', 'bidModifier', 'cpcBidMicros', 'cpmBidMicros', 'cpvBidMicros']));
                    $content['negative'] = (bool) ($content['negative'] ?? false);
                    if (Canonical::sort($content) === Canonical::sort($selection)) {
                        $matched = $row;
                    }
                }
                $next[] = $matched ?? [
                    'resourceName' => 'customers/1234567890/adGroupCriteria/201~'.(100 + count($next)),
                    'adGroup' => 'customers/1234567890/adGroups/201', 'status' => 'ENABLED', ...$selection,
                ];
            }
            usort($next, fn (array $a, array $b): int => strcmp($a['resourceName'], $b['resourceName']));
            $this->criteria = $next;
        });
        $this->app->instance(GoogleAdsService::class, $google);
    }

    private function tool(): NamespacedTool
    {
        return new NamespacedTool('campaign', app(EditGoogleAudienceTargeting::class));
    }

    private function request(array $changes, string $id): Request
    {
        return new Request(['campaign_id' => '101', 'ad_group_id' => '201', ...$changes], $id);
    }

    private function edit(Request $request): array
    {
        return json_decode((string) $this->tool()->handle($request), true, flags: JSON_THROW_ON_ERROR);
    }

    private function offerSegment(): void
    {
        $search = new NamespacedTool('campaign', app(SearchGoogleAudienceSegments::class));
        $result = json_decode((string) $search->handle(new Request(['ad_group_id' => '201', 'query' => 'Cardio', 'audience_mode' => 'OBSERVATION'])), true, flags: JSON_THROW_ON_ERROR);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
    }

    public function test_selected_segment_is_added_in_explicit_mode_and_preserves_demographics(): void
    {
        $this->offerSegment();
        $request = $this->request(['segment_resource' => self::SEGMENT, 'operation' => 'add', 'audience_mode' => 'OBSERVATION'], 'segment');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        app(Workspace::class)->rememberChoices([]);
        $result = $this->edit($request);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertTrue($result['verified']);
        $this->assertSame('OBSERVATION', $result['audience_mode']);
        $this->assertCount(2, $this->criteria);
        $this->assertSame('applied', CampaignChange::sole()->state);
    }

    public function test_multiple_searched_segments_are_offered_and_added_in_one_approved_change(): void
    {
        $search = new NamespacedTool('campaign', app(SearchGoogleAudienceSegments::class));
        $result = json_decode((string) $search->handle(new Request([
            'ad_group_id' => '201', 'queries' => ['Cardio', 'Fitness'], 'audience_mode' => 'OBSERVATION',
        ])), true, flags: JSON_THROW_ON_ERROR);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $choices = app(Choices::class)->drain();
        $this->assertTrue($choices[0]['multiple']);
        $this->assertSame([self::SEGMENT, self::OTHER_SEGMENT], array_column($choices[0]['options'], 'value'));
        app(Workspace::class)->rememberChoices($choices);

        $request = $this->request(['segment_resources' => [self::SEGMENT, self::OTHER_SEGMENT], 'operation' => 'add', 'audience_mode' => 'OBSERVATION'], 'segments');
        $approval = $this->tool()->shouldRequestApproval($request);
        $this->assertNotNull($approval);
        $this->assertStringContainsString('Cardio Equipment', json_encode($approval));
        $this->assertStringContainsString('Fitness Services', json_encode($approval));
        app(Workspace::class)->rememberChoices([]);
        $result = $this->edit($request);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertCount(3, $this->criteria);
        $this->assertSame('GENDER', $this->criteria[0]['type']);
        $this->assertSame('applied', CampaignChange::sole()->state);
    }

    public function test_unoffered_or_duplicate_segments_are_refused_without_a_write(): void
    {
        $this->offerSegment();
        $change = ['segment_resources' => [self::SEGMENT, self::OTHER_SEGMENT], 'operation' => 'add', 'audience_mode' => 'OBSERVATION'];
        $request = $this->request($change, 'unoffered');
        $this->assertNull($this->tool()->shouldRequestApproval($request));
        $result = $this->edit($request);
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('current Google audience search', $result['error']);

        $request = $this->request([...$change, 'segment_resources' => [self::SEGMENT, self::SEGMENT]], 'duplicate');
        $this->assertNull($this->tool()->shouldRequestApproval($request));
        $this->assertFalse($this->edit($request)['ok']);
        $this->assertDatabaseCount('campaign_changes', 0);
    }

    public function test_batch_approval_is_rejected_if_audience_changes_before_apply(): void
    {
        $search = new NamespacedTool('campaign', app(SearchGoogleAudienceSegments::class));
        $search->handle(new Request(['ad_group_id' => '201', 'queries' => ['Cardio', 'Fitness'], 'audience_mode' => 'OBSERVATION']));
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $request = $this->request(['segment_resources' => [self::SEGMENT, self::OTHER_SEGMENT], 'operation' => 'add', 'audience_mode' => 'OBSERVATION'], 'stale-batch');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $this->criteria[0]['negative'] = false;

        $result = $this->edit($request);

        $this->assertFalse($result['ok']);
        $this->assertFalse($result['reconciliation_required']);
        $this->assertDatabaseCount('campaign_changes', 0);
    }

    public function test_adding_a_batch_preserves_already_present_segments_with_their_bids(): void
    {
        $this->criteria[] = [
            'resourceName' => 'customers/1234567890/adGroupCriteria/201~2', 'adGroup' => 'customers/1234567890/adGroups/201',
            'type' => 'USER_INTEREST', 'status' => 'ENABLED', 'bidModifier' => 1.5,
            'userInterest' => ['userInterestCategory' => self::SEGMENT],
        ];
        $search = new NamespacedTool('campaign', app(SearchGoogleAudienceSegments::class));
        $search->handle(new Request(['ad_group_id' => '201', 'queries' => ['Cardio', 'Fitness'], 'audience_mode' => 'OBSERVATION']));
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $request = $this->request(['segment_resources' => [self::SEGMENT, self::OTHER_SEGMENT], 'operation' => 'add', 'audience_mode' => 'OBSERVATION'], 'existing-batch');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));

        $result = $this->edit($request);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertTrue($result['change']['segments'][0]['already_present']);
        $existing = collect($this->criteria)->first(fn (array $row): bool => data_get($row, 'userInterest.userInterestCategory') === self::SEGMENT);
        $this->assertEquals(1.5, $existing['bidModifier']);
        $this->assertCount(3, $this->criteria);
    }

    public function test_batch_is_not_written_if_a_segment_becomes_unavailable(): void
    {
        $search = new NamespacedTool('campaign', app(SearchGoogleAudienceSegments::class));
        $search->handle(new Request(['ad_group_id' => '201', 'queries' => ['Cardio', 'Fitness'], 'audience_mode' => 'OBSERVATION']));
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $request = $this->request(['segment_resources' => [self::SEGMENT, self::OTHER_SEGMENT], 'operation' => 'add', 'audience_mode' => 'OBSERVATION'], 'unavailable-batch');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $this->segmentAvailable = false;

        $result = $this->edit($request);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('no longer available', $result['error']);
        $this->assertDatabaseCount('campaign_changes', 0);
    }

    public function test_batch_cannot_change_which_segments_were_approved(): void
    {
        $search = new NamespacedTool('campaign', app(SearchGoogleAudienceSegments::class));
        $search->handle(new Request(['ad_group_id' => '201', 'queries' => ['Cardio', 'Fitness'], 'audience_mode' => 'OBSERVATION']));
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $change = ['segment_resources' => [self::SEGMENT, self::OTHER_SEGMENT], 'operation' => 'add', 'audience_mode' => 'OBSERVATION'];
        $this->assertNotNull($this->tool()->shouldRequestApproval($this->request($change, 'changed-batch')));

        $result = $this->edit($this->request([...$change, 'segment_resources' => [self::SEGMENT]], 'changed-batch'));

        $this->assertFalse($result['ok']);
        $this->assertFalse($result['reconciliation_required']);
        $this->assertDatabaseCount('campaign_changes', 0);
    }

    public function test_mode_change_preserves_other_restrictions_and_criteria(): void
    {
        $request = $this->request(['audience_mode' => 'TARGETING'], 'mode');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $result = $this->edit($request);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('TARGETING', $result['audience_mode']);
        $this->assertEquals(['targetingDimension' => 'PLACEMENT', 'bidOnly' => false], $this->restrictions[1]);
        $this->assertCount(1, $this->criteria);
    }

    public function test_missing_audience_restriction_uses_google_default_and_can_switch_to_observation(): void
    {
        $this->restrictions = [['targetingDimension' => 'GENDER', 'bidOnly' => true]];
        $request = $this->request(['audience_mode' => 'OBSERVATION'], 'implicit-mode');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $result = $this->edit($request);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('OBSERVATION', $result['audience_mode']);
        $this->assertEquals(['targetingDimension' => 'GENDER', 'bidOnly' => true], $this->restrictions[0]);
        $this->assertEquals(['targetingDimension' => 'AUDIENCE', 'bidOnly' => true], $this->restrictions[1]);
    }

    public function test_missing_choice_mode_and_stale_availability_are_refused(): void
    {
        $change = ['segment_resource' => self::SEGMENT, 'operation' => 'add', 'audience_mode' => 'OBSERVATION'];
        $this->assertFalse($this->edit($this->request($change, 'not-offered'))['ok']);
        $this->offerSegment();
        $this->assertNull($this->tool()->shouldRequestApproval($this->request(array_diff_key($change, ['audience_mode' => true]), 'no-mode')));
        $request = $this->request($change, 'stale');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $this->segmentAvailable = false;
        $this->assertFalse($this->edit($request)['ok']);
        $this->assertDatabaseCount('campaign_changes', 0);
    }

    public function test_unconfirmed_write_requires_reconciliation(): void
    {
        $this->ignoreUpdate = true;
        $request = $this->request(['audience_mode' => 'TARGETING'], 'unconfirmed');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $result = $this->edit($request);
        $this->assertFalse($result['ok']);
        $this->assertTrue($result['reconciliation_required']);
        $this->assertSame('failed', CampaignChange::sole()->state);
    }

    public function test_segment_name_changed_after_approval_is_refused(): void
    {
        $this->offerSegment();
        $request = $this->request(['segment_resource' => self::SEGMENT, 'operation' => 'add', 'audience_mode' => 'OBSERVATION'], 'renamed');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $this->segmentName = 'Different Audience';
        $this->assertFalse($this->edit($request)['ok']);
        $this->assertDatabaseCount('campaign_changes', 0);
    }
}
