<?php

namespace Tests\Feature;

use App\Agent\NamespacedTool;
use App\Agent\Tools\Campaign\EditGoogleDemographics;
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 GoogleChatDemographicsTest extends TestCase
{
    use RefreshDatabase;

    private array $criteria;

    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-demographics');
        $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->criteria = [
            ['resourceName' => 'customers/1234567890/adGroupCriteria/201~1', 'adGroup' => 'customers/1234567890/adGroups/201',
                'type' => 'GENDER', 'status' => 'ENABLED', 'gender' => ['type' => 'FEMALE']],
            ['resourceName' => 'customers/1234567890/adGroupCriteria/201~2', 'adGroup' => 'customers/1234567890/adGroups/201',
                'type' => 'USER_LIST', 'status' => 'ENABLED', 'userList' => ['userList' => 'customers/1234567890/userLists/33'], 'bidModifier' => 1.4],
        ];
        $google = Mockery::mock(GoogleAdsService::class)->makePartial();
        $google->shouldReceive('readCampaignStructure')->andReturn([
            'channel_type' => 'DISPLAY',
            'ad_groups' => [['id' => '201', 'type' => 'DISPLAY_STANDARD', 'target_restrictions' => [['targetingDimension' => 'AUDIENCE', 'bidOnly' => true]]]],
        ]);
        $google->shouldReceive('readManagerAudiences')->andReturnUsing(fn (): array => ['201' => $this->criteria]);
        $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(EditGoogleDemographics::class));
    }

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

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

    public function test_approved_demographic_edit_preserves_other_audiences_and_bid_modifiers(): void
    {
        $request = $this->request([
            ['type' => 'GENDER', 'value' => 'FEMALE', 'operation' => 'exclude'],
            ['type' => 'AGE_RANGE', 'value' => 'AGE_RANGE_18_24', 'operation' => 'exclude'],
        ], 'demographics');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $result = $this->edit($request);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertTrue($result['verified']);
        $audience = array_values(array_filter($this->criteria, fn (array $row): bool => $row['type'] === 'USER_LIST'));
        $this->assertCount(1, $audience);
        $this->assertSame(1.4, $audience[0]['bidModifier']);
        $this->assertCount(3, $this->criteria);
        $this->assertSame('applied', CampaignChange::sole()->state);
    }

    public function test_stale_approval_and_modified_demographic_bids_are_refused(): void
    {
        $changes = [['type' => 'GENDER', 'value' => 'FEMALE', 'operation' => 'exclude']];
        $request = $this->request($changes, 'stale');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $this->criteria[0]['bidModifier'] = 1.3;
        $this->assertFalse($this->edit($request)['ok']);
        $this->assertNull($this->tool()->shouldRequestApproval($this->request($changes, 'bid')));
        $this->assertDatabaseCount('campaign_changes', 0);
    }

    public function test_unconfirmed_write_requires_reconciliation(): void
    {
        $this->ignoreUpdate = true;
        $request = $this->request([['type' => 'GENDER', 'value' => 'FEMALE', 'operation' => 'exclude']], 'uncertain');
        $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);
    }
}
