<?php

namespace Tests\Feature;

use App\Campaigns\CampaignImporter;
use App\Models\AllowedAdAccount;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use RuntimeException;
use Tests\TestCase;

/**
 * Opening a Google campaign that is not in the configured account.
 *
 * adoptGoogle() read GoogleAdsConnection::shared() and took its customer id as
 * the account, always, because for as long as one account was permitted that
 * was the only account anything could be in. Once the allow list opened and
 * the flow began asking which of the manager's 76 children to buy on, a
 * campaign id from any other account could not be opened at all: the read went
 * to the configured customer, Google said the campaign did not exist, and that
 * is true of that account and useless to the buyer.
 *
 * The account is now taken from the caller when it names one. When it does not,
 * the configured account is still tried first - which is the whole of the
 * common case and costs nothing - and only a genuine miss with other accounts
 * permitted turns into a question. Sweeping every permitted account instead
 * would be one read each, 76 on this manager, to answer something the buyer can
 * answer in a click.
 */
class AGoogleCampaignCanBeAdoptedFromAnyPermittedAccountTest extends TestCase
{
    use RefreshDatabase;

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

        config([
            'platforms.guardrails.paused' => false,
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '123-456-7890',
            'services.google_ads.login_customer_id' => '803-900-0543',
        ]);
    }

    /** @var list<string> */
    private array $customersRead = [];

    /** The campaign exists in $holder and nowhere else. */
    private function fakeGoogleHolding(string $holder): void
    {
        $this->customersRead = [];

        Http::fake(function (Request $request) use ($holder) {
            if (str_contains($request->url(), 'oauth2.googleapis.com')) {
                return Http::response(['access_token' => 'token', 'expires_in' => 3600]);
            }

            if (preg_match('#/customers/(\d+)/googleAds:searchStream#', (string) $request->url(), $matches) !== 1) {
                return Http::response([]);
            }

            $customer = $matches[1];
            $this->customersRead[] = $customer;
            $query = (string) ($request->data()['query'] ?? '');

            // Another account's read finds nothing, which is what Google does.
            if ($customer !== $holder) {
                return Http::response([['results' => []]]);
            }

            if (str_contains($query, 'campaign_budget.reference_count')) {
                return Http::response([['results' => [[
                    'campaign' => [
                        'id' => '555000111',
                        'name' => 'Imported Search',
                        'status' => 'PAUSED',
                        'advertisingChannelType' => 'SEARCH',
                        'biddingStrategyType' => 'MAXIMIZE_CONVERSIONS',
                    ],
                    'campaignBudget' => ['amountMicros' => '10000000', 'referenceCount' => 1],
                ]]]]);
            }

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

    private function adopt(string $accountId = ''): mixed
    {
        $user = User::factory()->create();

        return app(CampaignImporter::class)->adoptGoogle('555000111', $user, $accountId);
    }

    /**
     * Exactly one permitted Google account.
     *
     * The allow list is the union of the table and the config, and a migration
     * seeds the table with the shared account - so configuring one more makes
     * two, and accountChoiceExists() is true. Deactivated here so "one
     * permitted account" is actually one.
     */
    private function onlyOnePermittedAccount(): void
    {
        AllowedAdAccount::query()->where('platform', 'google')->update(['is_active' => false]);
        config(['platforms.guardrails.allowed_ad_accounts' => ['google:1234567890']]);
    }

    /** One permitted account: nothing to ask, and nothing changes. */
    public function test_the_configured_account_is_used_when_it_is_the_only_one_permitted(): void
    {
        $this->onlyOnePermittedAccount();
        $this->fakeGoogleHolding('1234567890');

        $campaign = $this->adopt();

        $this->assertSame('1234567890', $campaign->ad_account_id);
        $this->assertSame(['1234567890'], array_values(array_unique($this->customersRead)));
    }

    /** A named account is read, not the configured one. */
    public function test_a_named_account_is_the_one_read(): void
    {
        config(['platforms.guardrails.allowed_ad_accounts' => ['google:1234567890', 'google:9876543210']]);
        $this->fakeGoogleHolding('9876543210');

        $campaign = $this->adopt('9876543210');

        $this->assertSame('9876543210', $campaign->ad_account_id);
        $this->assertSame(['9876543210'], array_values(array_unique($this->customersRead)));
        $this->assertNotContains('1234567890', $this->customersRead);
    }

    /** Dashes are how a buyer writes a customer id. */
    public function test_a_named_account_may_be_written_with_dashes(): void
    {
        config(['platforms.guardrails.allowed_ad_accounts' => ['google:1234567890', 'google:9876543210']]);
        $this->fakeGoogleHolding('9876543210');

        $this->assertSame('9876543210', $this->adopt('987-654-3210')->ad_account_id);
    }

    /**
     * The gap itself: not in the configured account, and others are permitted.
     *
     * This used to surface as "Google campaign profile could not be loaded",
     * which says nothing a buyer can act on.
     */
    public function test_a_campaign_in_another_account_asks_which_account_rather_than_failing(): void
    {
        config(['platforms.guardrails.allowed_ad_accounts' => ['google:1234567890', 'google:9876543210']]);
        $this->fakeGoogleHolding('9876543210');

        try {
            $this->adopt();
            $this->fail('adopting from the wrong account should not have succeeded');
        } catch (RuntimeException $e) {
            $this->assertStringContainsString('list_ad_accounts', $e->getMessage());
            $this->assertStringContainsString('555000111', $e->getMessage());
            $this->assertStringContainsString('1234567890', $e->getMessage(), 'the message should say where it looked');
        }

        // One read, against the configured account. Not 76.
        $this->assertSame(['1234567890'], array_values(array_unique($this->customersRead)));
    }

    /** With one permitted account there is nothing to ask, so the real error stands. */
    public function test_a_genuine_miss_with_one_account_still_reports_the_platform_error(): void
    {
        $this->onlyOnePermittedAccount();
        $this->fakeGoogleHolding('9876543210');

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('could not be loaded');

        $this->adopt();
    }

    /** An account off the allow list is refused before any request. */
    public function test_an_unpermitted_named_account_is_refused(): void
    {
        $this->onlyOnePermittedAccount();
        $this->fakeGoogleHolding('5555555555');

        $this->expectException(\Throwable::class);

        $this->adopt('5555555555');

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