<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Publishing\GooglePublisher;
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;

/**
 * delete_entity and edit_entity reach Google, with Google's own limits.
 *
 * Both were Meta-only. Delete was the one that could not simply be extended:
 * its whole point is the delivery guard, written after a campaign holding
 * 346.61 USD and 66,652 impressions was deleted in a cleanup of test
 * campaigns, and that guard runs on spend and impressions Google had no read
 * for.
 *
 * It also sat on removeResource(), which caught every failure and reported it.
 * That made every success check meaningless, and GooglePublisher::rollBack said
 * in as many words that "removeResource throws on a refusal rather than
 * reporting one" while it did not - so a Google rollback always claimed a clean
 * account. DeleteEntity's own notes describe where that ends: five live Google
 * campaigns left with no record of them here. The swallow outlived the write-up
 * of it; it is gone now, and these pin both halves.
 *
 * Edit is deliberately narrower on Google than on Meta. An ad group holds no
 * budget and no bid strategy there, and a Google ad cannot be edited in place
 * at all - GoogleRules::editableAfterPublish already records that "an ad's copy
 * is still replaced rather than edited".
 */
class AGoogleEntityCanBeDeletedOrEditedTest 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-delete');
        app(Workspace::class)->ownedBy($this->user);

        config([
            'platforms.guardrails.allowed_ad_accounts' => ['3460855874'],
            'platforms.guardrails.paused' => false,
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '3460855874',
        ]);
    }

    private function campaign(): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Knowledgedom',
            'platform' => 'google',
            'status' => 'published',
            'ad_account_id' => '3460855874',
            'external_campaign_id' => '222',
            'external_ids' => ['campaign_id' => '222', 'budget_id' => '777', 'ad_group_id' => '333', 'ad_id' => '444'],
        ]);

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

        return $campaign;
    }

    /**
     * @param  array<string,array{cost:string,impr:string}>  $metrics  keyed by entity id
     */
    private function fakeGoogle(array $metrics = [], bool $mutatesFail = false, bool $emptyReporting = false): void
    {
        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*googleAds:searchStream' => function (ClientRequest $request) use ($metrics, $emptyReporting) {
                $query = (string) ($request->data()['query'] ?? '');

                // The delivery read is the one that selects metrics; the
                // structure reads do not, which is how they are told apart.
                if (str_contains($query, 'metrics.cost_micros')) {
                    if ($emptyReporting) {
                        return Http::response([['results' => []]]);
                    }
                    $id = str_contains($query, 'FROM campaign') ? '222'
                        : (str_contains($query, 'FROM ad_group_ad') ? '444' : '333');
                    $seen = $metrics[$id] ?? ['cost' => '0', 'impr' => '0'];

                    $row = match (true) {
                        str_contains($query, 'FROM ad_group_ad') => ['adGroupAd' => ['ad' => ['id' => $id]]],
                        str_contains($query, 'FROM ad_group') => ['adGroup' => ['id' => $id]],
                        default => ['campaign' => ['id' => $id]],
                    };

                    return Http::response([['results' => [
                        [...$row, 'metrics' => ['costMicros' => $seen['cost'], 'impressions' => $seen['impr']]],
                    ]]]);
                }

                $rows = match (true) {
                    str_contains($query, 'FROM ad_group_criterion') => [],
                    str_contains($query, 'FROM ad_group_ad') => [[
                        'adGroupAd' => ['status' => 'ENABLED', 'ad' => ['id' => '444', 'name' => 'RSA']],
                        'adGroup' => ['id' => '333', 'name' => 'Brand'],
                    ]],
                    str_contains($query, 'FROM ad_group') => [[
                        'adGroup' => ['id' => '333', 'name' => 'Brand', 'status' => 'ENABLED'],
                        'campaign' => ['advertisingChannelType' => 'SEARCH'],
                    ]],
                    default => [],
                };

                return Http::response([['results' => $rows]]);
            },
            '*:mutate' => $mutatesFail
                ? Http::response(['error' => ['message' => 'Operation not permitted.']], 403)
                : Http::response(['results' => [['resourceName' => 'x']]]),
        ]);
    }

    private function invoke(string $tool, array $arguments): array
    {
        $resolved = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t): bool => $t->name() === 'campaign__'.$tool);

        $this->assertNotNull($resolved, "campaign__{$tool} is not registered");

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

    /** @return list<string> the resources actually removed */
    private function removed(): array
    {
        $names = [];

        foreach (Http::recorded() as [$request]) {
            if (str_contains($request->url(), ':mutate') && data_get($request->data(), 'operations.0.remove')) {
                $names[] = (string) data_get($request->data(), 'operations.0.remove');
            }
        }

        return $names;
    }

    // ---------------------------------------------------------------- delete

    public function test_an_ad_group_that_never_delivered_is_deleted(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->invoke('delete_entity', ['entity_type' => 'ad_group', 'ids' => ['333']]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['customers/3460855874/adGroups/333'], $this->removed());
    }

    /** An ad is keyed by its ad group and itself, as everything else on Google is. */
    public function test_an_ad_is_removed_under_its_compound_resource_name(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->invoke('delete_entity', ['entity_type' => 'ad', 'ids' => ['444']]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['customers/3460855874/adGroupAds/333~444'], $this->removed());
    }

    /**
     * The 9 Oct guard, on Google.
     *
     * Anything that ever ran is refused with the numbers, until somebody says
     * again that they mean it.
     */
    public function test_something_that_delivered_is_refused_with_its_numbers(): void
    {
        $this->campaign();
        $this->fakeGoogle(metrics: ['333' => ['cost' => '143222716', 'impr' => '7759']]);

        $result = $this->invoke('delete_entity', ['entity_type' => 'ad_group', 'ids' => ['333']]);

        $this->assertFalse($result['ok']);
        $this->assertSame(['spend' => 143.222716, 'impressions' => 7759], $result['delivered']['333']);
        $this->assertSame([], $this->removed(), 'something that had delivered was deleted anyway');
    }

    public function test_second_confirmation_does_not_bypass_unknown_reporting(): void
    {
        $this->campaign();
        $this->fakeGoogle(emptyReporting: true);
        $result = $this->invoke('delete_entity', ['entity_type' => 'ad_group', 'ids' => ['333'], 'delete_even_though_it_delivered' => true]);
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('Unknown spend is not zero', $result['error']);
        $this->assertSame([], $this->removed());
    }

    public function test_subcent_delivery_requires_acknowledgement_even_without_impressions(): void
    {
        $this->campaign();
        $this->fakeGoogle(metrics: ['333' => ['cost' => '1', 'impr' => '0']]);
        $result = $this->invoke('delete_entity', ['entity_type' => 'ad_group', 'ids' => ['333']]);
        $this->assertFalse($result['ok']);
        $this->assertSame(0.000001, $result['delivered']['333']['spend']);
        $this->assertSame([], $this->removed());
    }

    /** And goes through once they have been told and still want it gone. */
    public function test_it_proceeds_once_the_user_has_confirmed(): void
    {
        $this->campaign();
        $this->fakeGoogle(metrics: ['333' => ['cost' => '143222716', 'impr' => '7759']]);

        $result = $this->invoke('delete_entity', [
            'entity_type' => 'ad_group',
            'ids' => ['333'],
            'delete_even_though_it_delivered' => true,
        ]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['customers/3460855874/adGroups/333'], $this->removed());
    }

    /**
     * Delivery is read all-time, not over a window.
     *
     * A campaign that spent and then stopped must not read as never having run.
     * Asserted on the query, because a fake answers whatever it is asked and a
     * date segment would otherwise go unnoticed.
     */
    public function test_delivery_is_read_all_time(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $this->invoke('delete_entity', ['entity_type' => 'ad_group', 'ids' => ['333']]);

        $metricsQuery = collect(Http::recorded())
            ->map(fn (array $pair): string => (string) ($pair[0]->data()['query'] ?? ''))
            ->first(fn (string $q): bool => str_contains($q, 'metrics.cost_micros'));

        $this->assertNotNull($metricsQuery, 'delivery was never read');
        $this->assertStringNotContainsString('segments.date', $metricsQuery);
        $this->assertStringNotContainsString('DURING', $metricsQuery);
    }

    /** An id not under the campaign is refused before anything is removed. */
    public function test_an_unknown_id_is_refused_without_removing(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->invoke('delete_entity', ['entity_type' => 'ad_group', 'ids' => ['999']]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('999', $result['error']);
        $this->assertSame([], $this->removed());
    }

    /**
     * A refused removal is reported as a failure, not as a success.
     *
     * The half this is really about: while removeResource swallowed errors,
     * this returned ok with the id in "deleted" and the object still on the
     * account.
     */
    public function test_a_refused_removal_is_reported_as_failed(): void
    {
        $campaign = $this->campaign();
        $this->fakeGoogle(mutatesFail: true);

        $result = $this->invoke('delete_entity', ['entity_type' => 'campaign', 'ids' => ['222']]);

        $this->assertFalse($result['ok']);
        $this->assertArrayHasKey('222', $result['failed']);
        $this->assertStringContainsString('still on the account', $result['note']);
    }

    /** And the local id is kept, so the campaign does not become an orphan. */
    public function test_a_refused_campaign_removal_keeps_the_local_id(): void
    {
        $campaign = $this->campaign();
        $this->fakeGoogle(mutatesFail: true);

        $this->invoke('delete_entity', ['entity_type' => 'campaign', 'ids' => ['222']]);

        $this->assertSame('222', $campaign->fresh()->external_campaign_id, 'the id was cleared on a failed delete');
    }

    /** A confirmed campaign delete does clear it. */
    public function test_a_confirmed_campaign_delete_clears_the_local_id(): void
    {
        $campaign = $this->campaign();
        $this->fakeGoogle();

        $result = $this->invoke('delete_entity', ['entity_type' => 'campaign', 'ids' => ['222']]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertNull($campaign->fresh()->external_campaign_id);
        $this->assertSame('draft', $campaign->fresh()->status);
    }

    // ------------------------------------------------------------- rollback

    /**
     * A rollback that could not remove something says what it left.
     *
     * The return value Publisher records on the decision so the buyer is told
     * what is still on their account. This returned [] however it went.
     */
    public function test_a_failed_rollback_names_what_it_left_behind(): void
    {
        $campaign = $this->campaign();
        $this->fakeGoogle(mutatesFail: true);

        $left = app(GooglePublisher::class)->rollBack(
            $campaign,
            ['campaign_id' => '222', 'budget_id' => '777'],
            'tester',
        );

        $this->assertSame(['campaigns/222', 'campaignBudgets/777'], $left);
    }

    /** A clean rollback still reports nothing left. */
    public function test_a_clean_rollback_leaves_nothing(): void
    {
        $campaign = $this->campaign();
        $this->fakeGoogle();

        $left = app(GooglePublisher::class)->rollBack(
            $campaign,
            ['campaign_id' => '222', 'budget_id' => '777'],
            'tester',
        );

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

    // ------------------------------------------------------------------ edit

    public function test_an_ad_group_can_be_renamed(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->invoke('edit_entity', ['entity_type' => 'ad_group', 'id' => '333', 'name' => 'Brand exact']);

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

    /** The bid is sent in micros, and only the fields given are masked. */
    public function test_a_cpc_bid_is_sent_in_micros_and_masked(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $this->invoke('edit_entity', ['entity_type' => 'ad_group', 'id' => '333', 'cpc_bid' => 1.5]);

        $update = collect(Http::recorded())
            ->map(fn (array $pair): array => (array) $pair[0]->data())
            ->first(fn (array $data): bool => (bool) data_get($data, 'operations.0.update.cpcBidMicros'));

        $this->assertNotNull($update, 'no ad group update was sent');
        $this->assertSame('1500000', data_get($update, 'operations.0.update.cpcBidMicros'));
        $this->assertSame('cpc_bid_micros', data_get($update, 'operations.0.updateMask'));
    }

    /**
     * A Google ad is refused, and the refusal names what does work.
     *
     * Google replaces an ad rather than editing it, which the rules already
     * record. A partial edit reported as success would be worse than a refusal.
     */
    public function test_a_google_ad_cannot_be_edited_in_place(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->invoke('edit_entity', ['entity_type' => 'ad', 'id' => '444', 'headline' => 'New headline']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('cannot be edited in place', $result['error']);
        $this->assertStringContainsString('set_entity_status', $result['note']);
    }

    /**
     * A field that belongs to the campaign is named, not quietly dropped.
     *
     * An ad group has no budget on Google, so asking for one is a question with
     * no answer rather than a change that happened.
     */
    public function test_a_campaign_level_field_is_refused_and_points_at_push_changes(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->invoke('edit_entity', ['entity_type' => 'ad_group', 'id' => '333', 'budget' => 50]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('budget', $result['error']);
        $this->assertStringContainsString('push_changes', $result['note']);
    }

    /** An ad group not in the campaign is refused. */
    public function test_editing_an_unknown_ad_group_is_refused(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->invoke('edit_entity', ['entity_type' => 'ad_group', 'id' => '999', 'name' => 'Nope']);

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

    /** Nothing to change is said rather than reported as a no-op success. */
    public function test_an_edit_with_no_fields_is_refused(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->invoke('edit_entity', ['entity_type' => 'ad_group', 'id' => '333']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('Nothing to change', $result['error']);
    }

    /**
     * A campaign id that is not this campaign is refused, as a child id is.
     *
     * Only children were matched against the live structure. A campaign id the
     * model carried over from an earlier turn, or invented in the right shape,
     * went straight to campaigns:mutate as a remove without ever being read for
     * ownership - and the approval card names the campaign in focus, not the id,
     * so the buyer approves deleting one campaign and another is destroyed.
     * There is no undo on either platform.
     */
    public function test_a_campaign_id_from_somewhere_else_is_refused_before_anything_is_sent(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->invoke('delete_entity', ['entity_type' => 'campaign', 'ids' => ['999']]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('999', $result['error']);
        $this->assertStringContainsString('not part of this campaign', $result['error']);
        $this->assertSame([], $this->removed(), 'nothing may be removed when the id is not this campaign');
    }

    /** The campaign in focus is still deletable by its own id. */
    public function test_the_campaign_in_focus_is_still_deletable_by_its_own_id(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->invoke('delete_entity', ['entity_type' => 'campaign', 'ids' => ['222']]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['customers/3460855874/campaigns/222'], $this->removed());
    }
}
