<?php

namespace Tests\Feature;

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 ClientRequest;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * list_campaign_structure answers for Google, not only for Meta.
 *
 * It used to refuse by name: "Listing ad sets and ads is only available for
 * Meta campaigns." That was honest - nothing could read it. What looked like
 * the read already existing was app/Mcp/Tools/GoogleAds/ListAdGroups and
 * ListAds, which call $googleAds->listAdGroups() and ->listAds(); neither
 * method has ever existed on GoogleAdsService, and neither tool has ever been
 * registered, so the first call would have been a fatal rather than a list.
 * GoogleAdsService::search carries a comment about exactly this hazard - a
 * fatal in code nobody runs looks exactly like code that works.
 *
 * So the read is new, and the thing being tested is that a buyer on Google can
 * ask what is in their campaign and get ids they can then act on.
 *
 * Google's vocabulary is kept rather than mapped onto Meta's. A Performance Max
 * campaign has no ad groups at all - its creative lives in asset groups - so
 * reporting "two ad sets" would be a wrong answer dressed up as a consistent
 * one.
 */
class AGoogleCampaignCanBeListedTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

    protected function setUp(): void
    {
        parent::setUp();

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

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

        // Google is connected once for everybody, from config, which is what
        // GoogleAdsConnection::shared falls back to.
        config([
            'platforms.guardrails.allowed_ad_accounts' => ['*'],
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '346-085-5874',
        ]);
    }

    private function campaign(string $platform = 'google', ?string $externalId = '222'): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Knowledgedom Search',
            'platform' => $platform,
            'status' => $externalId === null ? 'draft' : 'published',
            'external_campaign_id' => $externalId,
        ]);

        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign);

        return $campaign;
    }

    /** One ad group, one ad under it, and nothing else. */
    private function adGroupRow(array $overrides = []): array
    {
        return [
            'adGroup' => [
                'id' => '333',
                'name' => 'Brand terms',
                'status' => 'ENABLED',
                'type' => 'SEARCH_STANDARD',
                'cpcBidMicros' => '1500000',
                ...$overrides,
            ],
            'campaign' => ['advertisingChannelType' => 'SEARCH'],
        ];
    }

    private function adRow(array $overrides = []): array
    {
        return [
            'adGroupAd' => [
                'status' => 'ENABLED',
                'policySummary' => ['approvalStatus' => 'APPROVED'],
                'ad' => [
                    'id' => '444',
                    'name' => 'RSA one',
                    'responsiveSearchAd' => [
                        'headlines' => [['text' => 'Cheap car cover'], ['text' => 'Fast quotes']],
                    ],
                ],
                ...$overrides,
            ],
            'adGroup' => ['id' => '333', 'name' => 'Brand terms'],
        ];
    }

    private function assetGroupRow(): array
    {
        return ['assetGroup' => [
            'id' => '555',
            'name' => 'Winter assets',
            'status' => 'ENABLED',
            'primaryStatus' => 'ELIGIBLE',
        ]];
    }

    /**
     * Answered by which table the GAQL reads from.
     *
     * "FROM ad_group_ad" is matched before "FROM ad_group", because the second
     * is a substring of the first and getting that the wrong way round would
     * serve ad rows to the ad-group query.
     */
    private function fakeGoogle(array $adGroups, array $ads, array $assetGroups = []): void
    {
        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*googleAds:searchStream' => function (ClientRequest $request) use ($adGroups, $ads, $assetGroups) {
                $query = (string) ($request->data()['query'] ?? '');

                $rows = match (true) {
                    str_contains($query, 'FROM ad_group_criterion') => [],
                    str_contains($query, 'FROM ad_group_ad') => $ads,
                    str_contains($query, 'FROM ad_group') => $adGroups,
                    str_contains($query, 'FROM asset_group') => $assetGroups,
                    default => [],
                };

                return Http::response([['results' => $rows]]);
            },
        ]);
    }

    private function list(array $arguments = []): array
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t): bool => $t->name() === 'campaign__list_campaign_structure');

        $this->assertNotNull($tool, 'campaign__list_campaign_structure is not registered');

        return json_decode((string) $tool->handle(new Request($arguments)), true);
    }

    /** @return list<string> every GAQL query actually sent */
    private function queries(): array
    {
        $queries = [];

        foreach (Http::recorded() as [$request]) {
            if (str_contains($request->url(), 'searchStream')) {
                $queries[] = (string) ($request->data()['query'] ?? '');
            }
        }

        return $queries;
    }

    // --------------------------------------------------------------- it answers

    /** The refusal this replaces. */
    public function test_a_google_campaign_is_no_longer_refused(): void
    {
        $this->campaign();
        $this->fakeGoogle([$this->adGroupRow()], [$this->adRow()]);

        $result = $this->list();

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('google', $result['platform']);
    }

    public function test_it_lists_the_ad_groups_with_their_ids_and_statuses(): void
    {
        $this->campaign();
        $this->fakeGoogle([$this->adGroupRow()], [$this->adRow()]);

        $group = $this->list()['ad_groups'][0];

        $this->assertSame('333', $group['id']);
        $this->assertSame('Brand terms', $group['name']);
        $this->assertSame('ENABLED', $group['status']);
        $this->assertSame(1.5, $group['cpc_bid'], 'the bid was not converted out of micros');
    }

    public function test_it_lists_the_ads_with_the_ad_group_they_sit_under(): void
    {
        $this->campaign();
        $this->fakeGoogle([$this->adGroupRow()], [$this->adRow()]);

        $ad = $this->list()['ads'][0];

        $this->assertSame('444', $ad['id']);
        $this->assertSame('333', $ad['ad_group_id']);
        $this->assertSame('Cheap car cover', $ad['headline'], 'the first headline was not read');
    }

    /** The count per ad group, so the model can say it without counting itself. */
    public function test_each_ad_group_carries_its_own_ad_count(): void
    {
        $this->campaign();
        $second = $this->adRow();
        $second['adGroupAd']['ad']['id'] = '445';

        $this->fakeGoogle([$this->adGroupRow()], [$this->adRow(), $second]);

        $result = $this->list();

        $this->assertSame(2, $result['ad_groups'][0]['ads']);
        $this->assertSame(['ad_groups' => 1, 'ads' => 2, 'asset_groups' => 0], $result['counts']);
    }

    /**
     * An ENABLED ad that serves nothing.
     *
     * Google's status says what the buyer set; approval says whether Google
     * will show it. Reporting only the first would call a disapproved ad
     * running, which is the Meta effective_status problem in Google's words.
     */
    public function test_a_disapproved_ad_is_reported_as_disapproved(): void
    {
        $this->campaign();
        $this->fakeGoogle(
            [$this->adGroupRow()],
            [$this->adRow(['policySummary' => ['approvalStatus' => 'DISAPPROVED']])],
        );

        $result = $this->list();

        $this->assertSame('ENABLED', $result['ads'][0]['status']);
        $this->assertSame('DISAPPROVED', $result['ads'][0]['approval_status']);
        $this->assertStringContainsString('DISAPPROVED', $result['note']);
    }

    // ------------------------------------------------------- performance max

    /**
     * No ad groups, so asset groups are where the creative is.
     *
     * The empty first result is the signal - Performance Max has nothing in
     * ad_group to find - which is why no extra read is needed to know the type.
     */
    public function test_performance_max_lists_its_asset_groups(): void
    {
        $this->campaign();
        $this->fakeGoogle([], [], [$this->assetGroupRow()]);

        $result = $this->list();

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame([], $result['ad_groups']);
        $this->assertSame('555', $result['asset_groups'][0]['id']);
        $this->assertSame('ELIGIBLE', $result['asset_groups'][0]['primary_status']);
        $this->assertSame(1, $result['counts']['asset_groups']);
    }

    /**
     * And it is told to call them asset groups, in Google's words.
     *
     * Asserted as the instruction rather than as the absence of the word "ad
     * set" - the note has to say the words it is ruling out in order to rule
     * them out, so matching on absence would fail on the sentence doing the
     * work.
     */
    public function test_the_asset_group_note_says_not_to_call_them_ad_sets(): void
    {
        $this->campaign();
        $this->fakeGoogle([], [], [$this->assetGroupRow()]);

        $note = $this->list()['note'];

        $this->assertStringContainsString('asset group(s), not ad sets or ad groups', $note);
        $this->assertStringContainsString('Performance Max', $note);
    }

    /**
     * Pausing one is not offered, because it cannot be done.
     *
     * setLiveStatus has a campaign, ad-group and ad level and no asset-group
     * level, so an offer to pause one would be a promise nothing can keep.
     */
    public function test_it_does_not_offer_to_pause_a_single_asset_group(): void
    {
        $this->campaign();
        $this->fakeGoogle([], [], [$this->assetGroupRow()]);

        $this->assertStringContainsString('not something this product can do yet', $this->list()['note']);
    }

    /**
     * A Search campaign does not pay for the asset-group read.
     *
     * Three reads, not two: ad groups, their ads, and their keywords. The
     * keyword read was added when edit_entity gained the ability to change the
     * keywords on a live ad group, because it asks for a complete set and
     * there has to be somewhere to read the current one. The asset-group read
     * is still the one that must not happen here.
     */
    public function test_a_search_campaign_does_not_query_asset_groups(): void
    {
        $this->campaign();
        $this->fakeGoogle([$this->adGroupRow()], [$this->adRow()]);

        $this->list();

        $this->assertCount(3, $this->queries(), 'an unexpected read was sent for a campaign that has ad groups');
        $this->assertStringNotContainsString('FROM asset_group', implode("\n", $this->queries()));
    }

    public function test_requested_google_settings_include_live_profile_and_targeting_criteria(): void
    {
        $this->campaign();
        $this->fakeGoogleSettings();

        $result = $this->list(['include_google_settings' => true]);
        $settings = $result['google_settings'];

        $this->assertTrue($result['ok']);
        $this->assertSame('PAUSED', $settings['campaign_profile']['data']['status']);
        $this->assertEquals(1.0, $settings['campaign_profile']['data']['target_cpa']);
        $this->assertSame(['level' => 'CUSTOMER'], $settings['campaign_profile']['data']['conversion_goals']);
        $this->assertSame('geoTargetConstants/2840', $settings['campaign_criteria']['data'][0]['location']['geoTargetConstant']);
        $this->assertSame('AGE_RANGE_25_34', $settings['ad_group_audiences']['data']['333'][0]['ageRange']['type']);
        $this->assertNull($settings['campaign_criteria']['error']);
    }

    public function test_failed_settings_read_is_reported_without_hiding_other_live_data(): void
    {
        $this->campaign();
        $this->fakeGoogleSettings(failCriteria: true);

        $result = $this->list(['include_google_settings' => true]);

        $this->assertTrue($result['ok']);
        $this->assertSame('PAUSED', $result['google_settings']['campaign_profile']['data']['status']);
        $this->assertNull($result['google_settings']['campaign_criteria']['data']);
        $this->assertStringContainsString('permission', $result['google_settings']['campaign_criteria']['error']);
        $this->assertNull($result['google_settings']['device_bid_adjustments']['data']);
        $this->assertStringContainsString('permission', $result['google_settings']['device_bid_adjustments']['error']);
        $this->assertSame('AGE_RANGE_25_34', $result['google_settings']['ad_group_audiences']['data']['333'][0]['ageRange']['type']);
    }

    public function test_google_settings_report_validated_device_adjustments_when_google_omits_neutral_modifiers(): void
    {
        $this->campaign();
        $this->fakeGoogleSettings(deviceCriteria: [
            ['type' => 'DEVICE', 'status' => 'ENABLED', 'device' => ['type' => 'MOBILE']],
            ['type' => 'DEVICE', 'status' => 'ENABLED', 'device' => ['type' => 'DESKTOP']],
            ['type' => 'DEVICE', 'status' => 'ENABLED', 'bidModifier' => 0, 'device' => ['type' => 'TABLET']],
        ]);

        $result = $this->list(['include_google_settings' => true]);

        $this->assertEquals(['MOBILE' => 1, 'DESKTOP' => 1, 'TABLET' => 0], $result['google_settings']['device_bid_adjustments']['data']);
        $this->assertNull($result['google_settings']['device_bid_adjustments']['error']);
    }

    public function test_google_settings_do_not_treat_invalid_device_criteria_as_neutral(): void
    {
        $this->campaign();
        $this->fakeGoogleSettings(deviceCriteria: [
            ['type' => 'DEVICE', 'status' => 'PAUSED', 'device' => ['type' => 'DESKTOP']],
        ]);

        $settings = $this->list(['include_google_settings' => true])['google_settings']['device_bid_adjustments'];

        $this->assertNull($settings['data']);
        $this->assertStringContainsString('complete, supported', $settings['error']);
    }

    public function test_google_settings_require_the_requested_campaign_to_be_in_focus(): void
    {
        $this->campaign();
        Http::fake();

        $result = $this->list(['campaign_id' => '999', 'include_google_settings' => true]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('not the campaign in focus', $result['error']);
        Http::assertNothingSent();
    }

    private function fakeGoogleSettings(bool $failCriteria = false, array $deviceCriteria = []): void
    {
        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*googleAds:searchStream' => function (ClientRequest $request) use ($failCriteria, $deviceCriteria) {
                $query = (string) ($request->data()['query'] ?? '');
                if ($failCriteria && str_contains($query, 'FROM campaign_criterion')) {
                    return Http::response(['error' => ['message' => 'User does not have permission.']], 403);
                }

                $rows = match (true) {
                    str_contains($query, 'FROM conversion_goal_campaign_config') => [[
                        'conversionGoalCampaignConfig' => [
                            'campaign' => 'customers/3460855874/campaigns/222',
                            'goalConfigLevel' => 'CUSTOMER',
                        ],
                    ]],
                    str_contains($query, 'FROM campaign_conversion_goal') => [],
                    str_contains($query, 'FROM campaign_criterion') => [[
                        'campaignCriterion' => [
                            'resourceName' => 'customers/3460855874/campaignCriteria/222~1',
                            'type' => 'LOCATION', 'status' => 'ENABLED',
                            'location' => ['geoTargetConstant' => 'geoTargetConstants/2840'],
                        ],
                    ], ...array_map(fn (array $criterion, int $index): array => ['campaignCriterion' => [
                        'resourceName' => 'customers/3460855874/campaignCriteria/222~'.($index + 2),
                        ...$criterion,
                    ]], $deviceCriteria, array_keys($deviceCriteria))],
                    str_contains($query, 'FROM ad_group_criterion') && str_contains($query, 'USER_LIST') => [[
                        'adGroupCriterion' => [
                            'resourceName' => 'customers/3460855874/adGroupCriteria/333~2',
                            'adGroup' => 'customers/3460855874/adGroups/333',
                            'type' => 'AGE_RANGE', 'status' => 'ENABLED',
                            'ageRange' => ['type' => 'AGE_RANGE_25_34'],
                        ],
                    ]],
                    str_contains($query, 'FROM ad_group_criterion') => [],
                    str_contains($query, 'FROM ad_group_ad') => [$this->adRow()],
                    str_contains($query, 'FROM ad_group') => [$this->adGroupRow()],
                    str_contains($query, 'FROM campaign') => [[
                        'campaign' => [
                            'id' => '222', 'name' => 'Search', 'status' => 'PAUSED',
                            'biddingStrategyType' => 'TARGET_CPA',
                            'targetCpa' => ['targetCpaMicros' => '1000000'],
                        ],
                        'campaignBudget' => ['amountMicros' => '5000000'],
                    ]],
                    default => [],
                };

                return Http::response([['results' => $rows]]);
            },
        ]);
    }

    // ---------------------------------------------------------------- scoping

    /** Naming one ad group reads only its ads, not every ad in the campaign. */
    public function test_naming_an_ad_group_scopes_the_ad_read_to_it(): void
    {
        $this->campaign();
        $this->fakeGoogle([$this->adGroupRow()], [$this->adRow()]);

        $this->list(['ad_set_id' => '333']);

        $adQuery = collect($this->queries())->first(fn (string $q): bool => str_contains($q, 'FROM ad_group_ad'));

        $this->assertStringContainsString('ad_group.id = 333', $adQuery);
        $this->assertStringNotContainsString('campaign.id = 222', $adQuery);
    }

    /** An id that is not a number never reaches Google. */
    public function test_a_non_numeric_ad_group_id_is_refused(): void
    {
        $this->campaign();
        $this->fakeGoogle([$this->adGroupRow()], [$this->adRow()]);

        $result = $this->list(['ad_set_id' => "333' OR '1'='1"]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('must be numeric', $result['error']);
    }

    public function test_a_non_numeric_campaign_id_is_refused(): void
    {
        $this->campaign();
        $this->fakeGoogle([], []);

        $result = $this->list(['campaign_id' => 'customers/1/campaigns/2']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('must be numeric', $result['error']);
    }

    // ------------------------------------------------------------- the edges

    /** Nothing there is said as nothing there, and nothing is offered on it. */
    public function test_an_empty_campaign_says_so_and_offers_nothing(): void
    {
        $this->campaign();
        $this->fakeGoogle([], [], []);

        $result = $this->list();

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertStringContainsString('no ad groups, ads or asset groups', $result['note']);
        $this->assertStringContainsString('do not offer to pause or edit', $result['note']);
    }

    /**
     * A platform error is not an empty campaign.
     *
     * The distinction the Meta side already draws, because the model otherwise
     * tells the buyer their campaign is empty when the read merely failed.
     */
    public function test_a_platform_error_is_not_reported_as_an_empty_campaign(): void
    {
        $this->campaign();

        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*googleAds:searchStream' => Http::response(['error' => ['message' => 'User does not have permission.']], 403),
        ]);

        $result = $this->list();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('permission', $result['error']);
        $this->assertStringContainsString('not an empty campaign', $result['note']);
    }

    /** Nor is a missing connection. */
    public function test_a_missing_connection_is_not_reported_as_an_empty_campaign(): void
    {
        config(['services.google_ads.refresh_token' => null, 'services.google_ads.customer_id' => null]);

        $this->campaign();
        Http::fake();

        $result = $this->list();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('not an empty campaign', $result['note']);
        Http::assertNothingSent();
    }

    /**
     * One odd row does not lose the rest of the answer.
     *
     * readCampaignSearchCriteria throws on an incomplete row, correctly - it
     * imports a baseline that gets edited and written back. This read is spoken
     * aloud and acted on by id, so a nameless ad group is a worse answer but a
     * safe one, where refusing to list anything is the worse failure.
     */
    public function test_a_row_missing_its_name_still_lists(): void
    {
        $this->campaign();
        $nameless = $this->adGroupRow();
        unset($nameless['adGroup']['name']);

        $this->fakeGoogle([$nameless], [$this->adRow()]);

        $result = $this->list();

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('333', $result['ad_groups'][0]['id']);
        $this->assertSame('', $result['ad_groups'][0]['name']);
    }

    /** A row with no id at all is dropped, since there is nothing to act on. */
    public function test_a_row_with_no_id_is_dropped(): void
    {
        $this->campaign();
        $this->fakeGoogle([$this->adGroupRow(), ['adGroup' => ['name' => 'Ghost']]], [$this->adRow()]);

        $result = $this->list();

        $this->assertCount(1, $result['ad_groups']);
        $this->assertSame(1, $result['counts']['ad_groups']);
    }

    /** An unpublished campaign has nothing on the platform to read. */
    public function test_an_unpublished_google_campaign_says_it_is_not_published(): void
    {
        $this->campaign(externalId: null);
        Http::fake();

        $result = $this->list();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('not been published', $result['error']);
        $this->assertStringContainsString('Google', $result['error']);
        Http::assertNothingSent();
    }

    // ------------------------------------------------- the other platforms

    /**
     * A platform this cannot serve is refused by name.
     *
     * This asserted LinkedIn was refused, which stopped being true: LinkedIn
     * grew its own branch here while the Google work sat unmerged. The point
     * of the test is that an unservable platform is named rather than
     * answered with an empty structure, which would read as "this campaign
     * has nothing in it", so it now uses a platform that genuinely is one.
     */
    public function test_a_platform_this_cannot_serve_is_refused_by_name(): void
    {
        $this->campaign('tiktok');
        Http::fake();

        $result = $this->list();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('Tiktok', $result['error']);
        Http::assertNothingSent();
    }

    /** Meta still answers in Meta's words, with ad sets. */
    public function test_meta_still_answers_with_ad_sets(): void
    {
        config(['platforms.guardrails.allowed_ad_accounts' => ['meta:*']]);

        $campaign = $this->campaign('meta');
        $campaign->forceFill(['ad_account_id' => 'act_111'])->save();

        Http::fake(['graph.facebook.com/*' => Http::response(['data' => []])]);

        $result = $this->list();

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertArrayHasKey('ad_sets', $result);
        $this->assertArrayNotHasKey('ad_groups', $result);
    }

    /**
     * The OAuth token is exchanged once per lifetime, not once per call.
     *
     * accessToken() ran on every single request and threw the result away:
     * measured at five exchanges for four Ads API calls. It sits outside
     * audited(), so CallLogger's read memoisation cannot help it, and the
     * structure reads pass fresh: true which disables memoisation anyway. The
     * cost was double latency on every Google operation and quota spent on
     * Google's token endpoint, none of it in an audit row.
     */
    public function test_the_access_token_is_exchanged_once_for_many_calls(): void
    {
        $this->campaign();
        $this->fakeGoogle([$this->adGroupRow()], [$this->adRow()]);

        $this->list();
        $this->list();

        $exchanges = collect(Http::recorded())
            ->filter(fn (array $pair): bool => str_contains((string) $pair[0]->url(), 'oauth2.googleapis.com'))
            ->count();

        $adsCalls = collect(Http::recorded())
            ->filter(fn (array $pair): bool => str_contains((string) $pair[0]->url(), 'googleads.googleapis.com'))
            ->count();

        $this->assertGreaterThan(1, $adsCalls, 'there must be several Ads calls for this to mean anything');
        $this->assertSame(1, $exchanges, 'one token covers every call made inside its lifetime');
    }

    /** An expired token is exchanged again rather than served stale. */
    public function test_an_expired_token_is_exchanged_again(): void
    {
        $this->campaign();
        $this->fakeGoogle([$this->adGroupRow()], [$this->adRow()]);

        $this->list();
        $this->travel(3600)->seconds();
        $this->list();

        $exchanges = collect(Http::recorded())
            ->filter(fn (array $pair): bool => str_contains((string) $pair[0]->url(), 'oauth2.googleapis.com'))
            ->count();

        $this->assertSame(2, $exchanges, 'the cached token has expired and must not be reused');
    }
}
