<?php

namespace Tests\Feature;

use App\Models\GoogleAdsConnection;
use App\Services\GoogleAdsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

/**
 * The accounts under the manager are read from the manager.
 *
 * A Google Ads login is a manager customer id with child accounts hanging off
 * it, and the account a campaign is bought on is one of those children.
 * childAccountOptions is the thing that would offer that choice, and it could
 * not: it read available_customer_ids off the connection, a column filled by
 * exactly one code path - the OAuth setup flow in GoogleAdsController - while
 * GoogleAdsConnection::shared() builds its connection from configuration and
 * never sets it. On the shared connection, which is the only connection the
 * product actually uses, the list was always empty.
 *
 * That is what removed the account step from the Google flow. GoogleRules
 * records it as "the flow asked which account with nothing on screen, and
 * stopped there" - a true description of the symptom, and the wrong conclusion
 * drawn from it. The children were never missing. A manager customer id is
 * configured and they are one call away.
 *
 * The call also returns each name, so the old shape - read N ids from the
 * column, then spend one customer read per id to name it - is now one call
 * rather than one plus N.
 */
class GoogleChildAccountsAreReadFromTheManagerTest extends TestCase
{
    use RefreshDatabase;

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

        config([
            // The manager used to have to be on this list too, because listing
            // the accounts under it is attributed to it and the allow list
            // guarded the enumeration. It no longer does: see
            // GoogleAdsService::fetchChildAccounts(), and
            // GoogleAccountSelectionReachesTheScreenTest for the enumeration
            // working without it. Left on the list here because these tests are
            // about where the children are read from, not about the guard.
            // Bare ids are Google's shape in this list.
            'platforms.guardrails.allowed_ad_accounts' => ['3460855874', '9999999999', '7777777777'],
            'platforms.guardrails.paused' => false,
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '346-085-5874',
            'services.google_ads.login_customer_id' => '999-999-9999',
        ]);
    }

    /** One child, one manager, one suspended account: only the first qualifies. */
    private function managerAnswers(array $clients): void
    {
        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*googleAds:searchStream' => Http::response([[
                'results' => array_map(
                    static fn (array $client): array => ['customerClient' => $client],
                    $clients,
                ),
            ]]),
        ]);
    }

    private function child(string $id, ?string $name = 'Knowledgedom', array $overrides = []): array
    {
        return [
            'clientCustomer' => 'customers/'.$id,
            'descriptiveName' => $name,
            'manager' => false,
            'status' => 'ENABLED',
            ...$overrides,
        ];
    }

    private function searchCalls(): int
    {
        $calls = 0;

        foreach (Http::recorded() as [$request]) {
            if (str_contains($request->url(), 'searchStream')) {
                $calls++;
            }
        }

        return $calls;
    }

    private function offered(?GoogleAdsConnection $connection = null): array
    {
        return app(GoogleAdsService::class)->childAccountOptions(
            $connection ?? GoogleAdsConnection::shared(),
        );
    }

    // ------------------------------------------------------- the fallback

    /** The case that mattered: a shared connection with no stored list. */
    public function test_the_children_are_read_from_the_manager_when_nothing_is_stored(): void
    {
        $this->managerAnswers([$this->child('3460855874')]);

        $this->assertSame(
            [['customer_id' => '3460855874', 'name' => 'Knowledgedom']],
            $this->offered(),
        );
    }

    /** The shared connection really does carry no list, which is the premise. */
    public function test_the_shared_connection_stores_no_list_of_its_own(): void
    {
        $this->assertSame([], GoogleAdsConnection::shared()->available_customer_ids ?? []);
    }

    /** One call, not one plus one per child. */
    public function test_it_costs_a_single_read(): void
    {
        $this->managerAnswers([
            $this->child('3460855874'),
            $this->child('1111111111', 'Second account'),
            $this->child('2222222222', 'Third account'),
        ]);

        $this->assertCount(3, $this->offered());
        $this->assertSame(1, $this->searchCalls(), 'naming the children cost an extra read each');
    }

    /** The name comes back with the id, from the same row. */
    public function test_each_child_is_named(): void
    {
        $this->managerAnswers([$this->child('3460855874', 'Knowledgedom')]);

        $this->assertSame('Knowledgedom', $this->offered()[0]['name']);
    }

    /** A child with no name is still usable, since the id is what gets acted on. */
    public function test_a_child_with_no_name_falls_back_to_its_id(): void
    {
        $this->managerAnswers([$this->child('3460855874', null)]);

        $this->assertSame('Google Ads account 3460855874', $this->offered()[0]['name']);
    }

    /**
     * The name is asked for in the query, not just read out of the answer.
     *
     * Asserted on the GAQL because the fake answers whatever it is asked:
     * dropping descriptive_name from the SELECT would leave every test above
     * still passing while the live call returned nameless rows and fell back
     * to "Google Ads account <id>" for all of them. This is the assertion that
     * holds the one-call shape in place.
     */
    public function test_the_query_asks_the_manager_for_the_names(): void
    {
        $this->managerAnswers([$this->child('3460855874')]);

        $this->offered();

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

        $this->assertNotNull($query, 'the manager was never asked for its children');
        $this->assertStringContainsString('customer_client.descriptive_name', $query);
    }

    // ------------------------------------------------------- what is excluded

    /**
     * A row that does not say whether it is a manager is not offered.
     *
     * Failing towards exclusion: offering a manager as somewhere to buy ads
     * produces a campaign that cannot be created, while leaving out an account
     * that should have been there is visible and askable.
     */
    public function test_a_row_that_does_not_say_is_not_offered(): void
    {
        $child = $this->child('3460855874');
        $silent = $this->child('8888888888', 'Unknown shape');
        unset($silent['manager']);

        $this->managerAnswers([$child, $silent]);

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

    /** The same account twice is one option. */
    public function test_a_duplicated_child_is_offered_once(): void
    {
        $this->managerAnswers([$this->child('3460855874'), $this->child('3460855874')]);

        $this->assertCount(1, $this->offered());
    }

    /** Managers are not places to buy ads, so they are not offered. */
    public function test_a_nested_manager_is_not_offered(): void
    {
        $this->managerAnswers([
            $this->child('3460855874'),
            $this->child('5555555555', 'Sub manager', ['manager' => true]),
        ]);

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

    /** Nor is a closed or suspended one. */
    public function test_an_account_that_is_not_enabled_is_not_offered(): void
    {
        $this->managerAnswers([
            $this->child('3460855874'),
            $this->child('6666666666', 'Closed', ['status' => 'CANCELED']),
        ]);

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

    /** And the manager itself never appears among its own children. */
    public function test_the_manager_is_not_offered_as_one_of_its_children(): void
    {
        $this->managerAnswers([
            $this->child('3460855874'),
            $this->child('9999999999', 'The manager'),
        ]);

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

    // -------------------------------------------------- the stored list wins

    /**
     * A connection that carries its own list keeps it.
     *
     * The OAuth flow persists what that user consented to, so narrowing the
     * offer to it is deliberate rather than stale, and must not be widened
     * back to everything under the manager.
     */
    public function test_a_stored_list_is_used_instead_of_the_manager(): void
    {
        $connection = new GoogleAdsConnection([
            'customer_id' => '3460855874',
            'manager_customer_id' => '9999999999',
            'refresh_token' => 'refresh-token',
            'available_customer_ids' => ['7777777777'],
        ]);

        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*googleAds:searchStream' => Http::response([[
                'results' => [['customer' => ['id' => '7777777777', 'descriptiveName' => 'Consented account']]],
            ]]),
        ]);

        $this->assertSame(
            [['customer_id' => '7777777777', 'name' => 'Consented account']],
            app(GoogleAdsService::class)->childAccountOptions($connection),
        );
    }

    /** The manager is stripped out of a stored list too. */
    public function test_the_manager_is_stripped_from_a_stored_list(): void
    {
        $connection = new GoogleAdsConnection([
            'customer_id' => '3460855874',
            'manager_customer_id' => '999-999-9999',
            'refresh_token' => 'refresh-token',
            'available_customer_ids' => ['999-999-9999'],
        ]);

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

        $this->assertSame([], app(GoogleAdsService::class)->childAccountOptions($connection));
    }

    // ------------------------------------------------- the ids-only contract

    /**
     * The setup flow stores ids, so it still gets ids.
     *
     * GoogleAdsController merges the result into available_customer_ids, which
     * is cast to an array of strings - handing it rows would have written
     * arrays into that column.
     */
    public function test_the_ids_only_caller_still_gets_plain_ids(): void
    {
        $this->managerAnswers([$this->child('3460855874'), $this->child('1111111111', 'Second')]);

        $this->assertSame(
            ['3460855874', '1111111111'],
            app(GoogleAdsService::class)->fetchChildAccountIds(GoogleAdsConnection::shared()),
        );
    }

    /** With no manager configured there is nothing to enumerate, and it says so. */
    public function test_no_manager_is_an_explained_refusal(): void
    {
        config(['services.google_ads.login_customer_id' => null]);
        Http::fake();

        $this->expectExceptionMessage('Select a manager customer before loading child accounts.');

        try {
            $this->offered();
        } finally {
            Http::assertNothingSent();
        }
    }
}
