<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\LaunchFlow;
use App\Campaigns\Platforms\GoogleRules;
use App\Models\ArtifactFieldSource;
use App\Models\Campaign;
use App\Models\GoogleAdsConnection;
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;

/**
 * A Google buyer picks which account under the manager, when there is a choice.
 *
 * A Google login is a manager customer id with child accounts under it, and the
 * account a campaign is bought on is one of those children. The step that asked
 * which one was removed, and the recorded reason was that it "asked which
 * account with nothing on screen, and stopped there". That was true: the only
 * thing that could list the children read available_customer_ids, a column
 * filled by the OAuth setup flow alone, and the shared connection is built from
 * configuration and never has it. A resolver bug, not an absence of accounts.
 *
 * With the children readable the question is answerable, so the step is back -
 * but only where there is something to answer. One permitted account is not a
 * choice: it is filled in when the campaign is created, exactly as before, and
 * no question is asked. That distinction is most of this file.
 *
 * list_ad_accounts offers and verify_ad_account records, which is the division
 * Meta already uses.
 */
class AGoogleBuyerPicksTheAccountTest 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-account');
        app(Workspace::class)->ownedBy($this->user);

        config([
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '3460855874',
            'services.google_ads.login_customer_id' => '8039000543',
        ]);
    }

    /** Two children permitted, which is what makes it a question. */
    private function twoPermitted(): void
    {
        config(['platforms.guardrails.allowed_ad_accounts' => [
            '3460855874', '1111111111', '8039000543',
        ]]);
    }

    private function onePermitted(): void
    {
        config(['platforms.guardrails.allowed_ad_accounts' => ['3460855874']]);
    }

    private function campaign(): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Knowledgedom',
            'platform' => 'google',
            'status' => 'draft',
            'campaign_type' => 'search',
            'landing_url' => 'https://example.com/offer',
            'objective' => 'LEADS',
        ]);

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

        return $campaign;
    }

    /** The manager answers with its children; a customer read answers with one. */
    private function fakeGoogle(array $children): void
    {
        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*googleAds:searchStream' => function (ClientRequest $request) use ($children) {
                $query = (string) ($request->data()['query'] ?? '');

                if (! str_contains($query, 'FROM customer_client')) {
                    return Http::response([['results' => []]]);
                }

                return Http::response([['results' => array_map(
                    static fn (array $child): array => ['customerClient' => [
                        'clientCustomer' => 'customers/'.$child[0],
                        'descriptiveName' => $child[1],
                        'manager' => false,
                        'status' => 'ENABLED',
                    ]],
                    $children,
                )]]);
            },
        ]);
    }

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

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

        return $tool;
    }

    private function list(): array
    {
        return json_decode((string) $this->tool('list_ad_accounts')->handle(new Request([])), true);
    }

    private function verify(string $id): array
    {
        return json_decode(
            (string) $this->tool('verify_ad_account')->handle(new Request(['ad_account_id' => $id])),
            true,
        );
    }

    /** @return list<string> */
    private function steps(Campaign $campaign): array
    {
        return collect(app(LaunchFlow::class)->progress($campaign->fresh()))
            ->pluck('key')
            ->all();
    }

    // ------------------------------------------------------------ it is asked

    public function test_the_account_is_asked_when_more_than_one_is_permitted(): void
    {
        $this->twoPermitted();

        $this->assertContains('ad_account', $this->steps($this->campaign()));
    }

    /** And it is not, when there is nothing to choose between. */
    public function test_the_account_is_not_asked_when_only_one_is_permitted(): void
    {
        $this->onePermitted();

        $this->assertNotContains('ad_account', $this->steps($this->campaign()));
    }

    /**
     * A wildcard is a choice, because it stands for a list nobody has seen.
     *
     * Spelled google:* rather than *, because a bare entry has to say which
     * platform it belongs to and Guardrails reads an unqualified one as not
     * being Google's.
     */
    public function test_a_google_wildcard_is_treated_as_a_choice(): void
    {
        config(['platforms.guardrails.allowed_ad_accounts' => ['google:*']]);

        $this->assertContains('ad_account', $this->steps($this->campaign()));
    }

    /**
     * But not with no manager configured, where there are no children at all.
     *
     * The wildcard cannot stand for a list that cannot be read: without a
     * login customer id the only account this instance knows of is the
     * configured one, and treating it as a choice sent the flow to ask a
     * question whose only possible answer was "Select a manager customer
     * before loading child accounts".
     */
    public function test_a_wildcard_with_no_manager_is_not_a_choice(): void
    {
        config([
            'platforms.guardrails.allowed_ad_accounts' => ['google:*'],
            'services.google_ads.login_customer_id' => null,
        ]);

        $this->assertNotContains('ad_account', $this->steps($this->campaign()));
        $this->assertSame('3460855874', app(GoogleRules::class)->defaultAdAccountId());
    }

    /** The step names the tool that answers it. */
    public function test_the_step_names_list_ad_accounts(): void
    {
        $this->twoPermitted();

        $step = collect(app(LaunchFlow::class)->steps($this->campaign()))
            ->firstWhere('key', 'ad_account');

        $this->assertNotNull($step);
        $this->assertSame('list_ad_accounts', $step['tool']);
    }

    // --------------------------------------------------------- what is offered

    public function test_the_children_of_the_manager_are_offered(): void
    {
        $this->twoPermitted();
        $this->campaign();
        $this->fakeGoogle([['3460855874', 'Knowledgedom'], ['1111111111', 'Second account']]);

        $result = $this->list();

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('google', $result['platform']);
        $this->assertSame(
            [['customer_id' => '3460855874', 'name' => 'Knowledgedom'],
                ['customer_id' => '1111111111', 'name' => 'Second account']],
            $result['ad_accounts'],
        );
    }

    public function test_explicit_google_account_listing_works_without_a_focused_campaign_and_filters_permissions(): void
    {
        $this->onePermitted();
        $this->fakeGoogle([['3460855874', 'Allowed'], ['1111111111', 'Not allowed']]);

        $result = json_decode((string) $this->tool('list_ad_accounts')->handle(new Request(['platform' => 'google'])), true);

        $this->assertTrue($result['ok']);
        $this->assertSame('google', $result['platform']);
        $this->assertSame([['customer_id' => '3460855874', 'name' => 'Allowed']], $result['ad_accounts']);
        $this->assertNull(app(Workspace::class)->focus());
    }

    public function test_explicit_google_account_listing_does_not_change_focused_campaign(): void
    {
        $this->twoPermitted();
        $campaign = $this->campaign();
        $this->fakeGoogle([['3460855874', 'Allowed'], ['1111111111', 'Second']]);
        $originalAccount = $campaign->ad_account_id;

        $result = json_decode((string) $this->tool('list_ad_accounts')->handle(new Request(['platform' => 'google'])), true);

        $this->assertCount(2, $result['ad_accounts']);
        $this->assertSame($originalAccount, $campaign->fresh()->ad_account_id);
    }

    /**
     * An account the manager has but the allow list does not is not offered.
     *
     * Filtered rather than merely bounded. Offering it would reproduce campaign
     * 97 one step earlier: the buyer picks it, answers everything else, and
     * meets "not on the allowed list" at publish.
     */
    public function test_an_account_that_is_not_allow_listed_is_not_offered(): void
    {
        $this->twoPermitted();
        $this->campaign();
        $this->fakeGoogle([
            ['3460855874', 'Knowledgedom'],
            ['1111111111', 'Second account'],
            ['2222222222', 'Not permitted'],
        ]);

        $this->assertSame(
            ['3460855874', '1111111111'],
            array_column($this->list()['ad_accounts'], 'customer_id'),
        );
    }

    /** Listing writes nothing; the answer is what writes. */
    public function test_listing_does_not_set_the_account(): void
    {
        $this->twoPermitted();
        $campaign = $this->campaign();
        $this->fakeGoogle([['3460855874', 'Knowledgedom'], ['1111111111', 'Second account']]);

        $this->list();

        $this->assertNull($campaign->fresh()->ad_account_id, 'listing picked an account on the buyer\'s behalf');
    }

    /** Nothing permitted under the manager is an administrator's problem. */
    public function test_no_permitted_child_is_an_explained_refusal(): void
    {
        $this->twoPermitted();
        $this->campaign();
        $this->fakeGoogle([['9999999999', 'Someone else']]);

        $result = $this->list();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('on the allowed list', $result['error']);
        $this->assertStringContainsString('administrator', $result['note']);
    }

    /**
     * A manager that cannot be read falls back rather than stranding the buyer.
     *
     * This is what the product did for months, the allow list still has to
     * pass, and a Google hiccup at the first question should not stop a flow
     * that was about to use the configured account anyway.
     */
    public function test_a_failed_manager_read_falls_back_to_the_configured_account(): void
    {
        $this->twoPermitted();
        $campaign = $this->campaign();

        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*googleAds:searchStream' => Http::response(['error' => ['message' => 'Backend error.']], 500),
        ]);

        $result = $this->list();

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('3460855874', $result['ad_account_id']);
        $this->assertSame('3460855874', $campaign->fresh()->ad_account_id);
    }

    // -------------------------------------------------------- what is recorded

    public function test_the_chosen_account_is_recorded(): void
    {
        $this->twoPermitted();
        $campaign = $this->campaign();
        $this->fakeGoogle([['3460855874', 'Knowledgedom'], ['1111111111', 'Second account']]);

        $result = $this->verify('1111111111');

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('1111111111', $campaign->fresh()->ad_account_id);
        $this->assertSame('Second account', $result['name']);
    }

    /** Recorded as the buyer's answer, because on Google that is what it is. */
    public function test_the_choice_is_recorded_as_the_users_own(): void
    {
        $this->twoPermitted();
        $campaign = $this->campaign();
        $this->fakeGoogle([['3460855874', 'Knowledgedom'], ['1111111111', 'Second account']]);

        $this->verify('1111111111');

        $this->assertSame(
            ArtifactFieldSource::USER_STATED,
            app(Workspace::class)->sourcesFor($campaign->fresh())['ad_account_id'] ?? null,
        );
    }

    /** And answering completes the step. */
    public function test_answering_completes_the_step(): void
    {
        $this->twoPermitted();
        $campaign = $this->campaign();
        $this->fakeGoogle([['3460855874', 'Knowledgedom'], ['1111111111', 'Second account']]);

        $this->verify('1111111111');

        $step = collect(app(LaunchFlow::class)->progress($campaign->fresh()))
            ->firstWhere('key', 'ad_account');

        $this->assertTrue((bool) ($step['done'] ?? false), 'the step did not complete once the account was chosen');
    }

    /** A dashed id is the same id. */
    public function test_a_dashed_customer_id_is_accepted(): void
    {
        $this->twoPermitted();
        $campaign = $this->campaign();
        $this->fakeGoogle([['3460855874', 'Knowledgedom'], ['1111111111', 'Second account']]);

        $this->assertTrue($this->verify('346-085-5874')['ok']);
        $this->assertSame('3460855874', $campaign->fresh()->ad_account_id);
    }

    // ------------------------------------------------------- what is refused

    /**
     * An id the manager does not have is refused even if it is allow-listed.
     *
     * The allow list says what may be bought on, not what exists. Writing an
     * id that passes the guard but is not under the manager would fail at
     * publish, which is the failure this step exists to prevent.
     */
    public function test_an_allow_listed_id_the_manager_does_not_have_is_refused(): void
    {
        $this->twoPermitted();
        $campaign = $this->campaign();
        $this->fakeGoogle([['3460855874', 'Knowledgedom']]);

        $result = $this->verify('1111111111');

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('not one of the accounts under this Google Ads manager', $result['error']);
        $this->assertNull($campaign->fresh()->ad_account_id);
    }

    /** An id that is not on the allow list never reaches the manager. */
    public function test_an_id_that_is_not_allow_listed_is_refused(): void
    {
        $this->twoPermitted();
        $campaign = $this->campaign();
        Http::fake();

        $result = $this->verify('2222222222');

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('not on the allowed list', $result['error']);
        $this->assertNull($campaign->fresh()->ad_account_id);
        Http::assertNothingSent();
    }

    /** A Meta-shaped id is named as Meta's rather than passed along. */
    public function test_a_meta_shaped_id_is_refused_by_shape(): void
    {
        $this->twoPermitted();
        $this->campaign();
        Http::fake();

        $result = $this->verify('act_1418821929380936');

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('not on the allowed list', $result['error']);
        Http::assertNothingSent();
    }

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

        $result = $this->verify('');

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

    /**
     * Changing the account drops the conversion action chosen under the old one.
     *
     * A conversion action belongs to the account it was read from, so it cannot
     * survive a move. Cleared here rather than left to fail at publish against
     * an account that has never heard of it.
     */
    public function test_changing_the_account_clears_the_conversion_action(): void
    {
        $this->twoPermitted();
        $campaign = $this->campaign();
        $campaign->forceFill([
            'ad_account_id' => '3460855874',
            'pixel_id' => 'customers/3460855874/conversionActions/555',
        ])->save();

        $this->fakeGoogle([['3460855874', 'Knowledgedom'], ['1111111111', 'Second account']]);

        $result = $this->verify('1111111111');

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertNull($campaign->fresh()->pixel_id, 'the conversion action survived a change of account');
        $this->assertSame(['pixel_id'], $result['cleared_because_account_changed']);
    }

    /** Re-picking the same account clears nothing. */
    public function test_choosing_the_same_account_again_clears_nothing(): void
    {
        $this->twoPermitted();
        $campaign = $this->campaign();
        $campaign->forceFill([
            'ad_account_id' => '3460855874',
            'pixel_id' => 'customers/3460855874/conversionActions/555',
        ])->save();

        $this->fakeGoogle([['3460855874', 'Knowledgedom'], ['1111111111', 'Second account']]);

        $result = $this->verify('3460855874');

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('customers/3460855874/conversionActions/555', $campaign->fresh()->pixel_id);
        $this->assertArrayNotHasKey('cleared_because_account_changed', $result);
    }

    /**
     * The chosen account is the account every call goes to.
     *
     * Choosing a child of the manager recorded the id on the campaign and
     * changed nothing else: every Google call still resolved its customer from
     * GOOGLE_ADS_CUSTOMER_ID. Publishing refused the campaign at the last step
     * for not matching, and the reads that did run looked at the configured
     * account, so a campaign's own ad groups came back as "not part of this
     * campaign". The buyer had answered the question correctly and there was no
     * step to go back to.
     */
    public function test_the_connection_follows_the_account_the_buyer_chose(): void
    {
        config(['services.google_ads.customer_id' => '3460855874']);

        $shared = GoogleAdsConnection::shared();
        $this->assertSame('3460855874', $shared->customer_id);

        $chosen = $shared->onCustomer('9988776655');

        $this->assertSame('9988776655', $chosen->customer_id, 'the chosen account must win');
        $this->assertSame($shared->refresh_token, $chosen->refresh_token, 'the credentials are the install\'s');
        $this->assertSame($shared->manager_customer_id, $chosen->manager_customer_id, 'the manager is what lets a child be addressed');
        $this->assertSame('3460855874', $shared->customer_id, 'the shared connection is not mutated');
    }

    /** A blank or identical id leaves the connection exactly as it was. */
    public function test_no_account_on_the_campaign_leaves_the_connection_alone(): void
    {
        config(['services.google_ads.customer_id' => '3460855874']);
        $shared = GoogleAdsConnection::shared();

        $this->assertSame($shared, $shared->onCustomer(null));
        $this->assertSame($shared, $shared->onCustomer(''));
        $this->assertSame($shared, $shared->onCustomer('346-085-5874'));
    }
}
