<?php

namespace Tests\Feature;

use App\Agent\Choices;
use App\Agent\Tools\Campaign\ListAdAccounts;
use App\Agent\Workspace;
use App\Campaigns\Platforms\GoogleRules;
use App\Models\Campaign;
use App\Models\GoogleAdsConnection;
use App\Models\User;
use App\Services\GoogleAdsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * "There is no option for account selection."
 *
 * Reported against a live Google campaign that was published to account
 * 3460855874 without the buyer ever being asked. Two things were in the way,
 * and the first hid the second.
 *
 * The allow list guarded the enumeration. Listing the accounts under a manager
 * is attributed to the manager, and the manager is not an account anyone
 * publishes to, so it was never on the list. fetchChildAccounts threw,
 * ListAdAccounts caught it as a warning, and the flow fell back to "Google runs
 * on one shared account, do not ask the user to choose". The question therefore
 * could not appear however many child accounts were permitted - an
 * administrator would have had to grant write access to the manager to get a
 * choice between two children.
 *
 * And Google's branch never put the accounts on screen. Meta's has always
 * offered buttons; Google's handed the model a list to read out, so the one
 * platform with 78 accounts under its manager was the one asking a buyer to
 * type a ten-digit customer id.
 *
 * Checked live against manager 8039000543: 78 enabled accounts, and with two of
 * them permitted both now arrive as buttons.
 */
class GoogleAccountSelectionReachesTheScreenTest 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' => '346-085-5874',
            'services.google_ads.login_customer_id' => '803-900-0543',
        ]);
    }

    /** @param  list<array{id: string, name: string}>  $children */
    private function managerHas(array $children): void
    {
        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*googleAds:searchStream' => Http::response([[
                'results' => array_map(static fn (array $child): array => ['customerClient' => [
                    'clientCustomer' => 'customers/'.$child['id'],
                    'descriptiveName' => $child['name'],
                    'manager' => false,
                    'status' => 'ENABLED',
                ]], $children),
            ]]),
        ]);
    }

    private function campaign(): Campaign
    {
        $user = User::factory()->create();
        $this->actingAs($user);

        $campaign = Campaign::create([
            'user_id' => $user->getKey(),
            'name' => 'Account selection',
            'platform' => 'google',
            'campaign_type' => 'search',
            'status' => 'draft',
        ]);

        app(Workspace::class)->bindTo('account-selection');
        app(Workspace::class)->focusOn($campaign);

        return $campaign;
    }

    public function test_the_children_are_listed_without_the_manager_being_on_the_allowed_list(): void
    {
        // The manager, 8039000543, is deliberately absent.
        config(['platforms.guardrails.allowed_ad_accounts' => ['3460855874', '3267101439']]);
        $this->managerHas([
            ['id' => '3460855874', 'name' => 'knowledgedomain'],
            ['id' => '3267101439', 'name' => '3DayBlinds'],
        ]);

        $accounts = app(GoogleAdsService::class)
            ->childAccountOptions(GoogleAdsConnection::shared());

        $this->assertSame(
            ['3460855874', '3267101439'],
            array_column($accounts, 'customer_id'),
            'the enumeration was refused because the manager is not an account anyone publishes to',
        );
    }

    public function test_two_permitted_accounts_arrive_as_buttons(): void
    {
        config(['platforms.guardrails.allowed_ad_accounts' => ['3460855874', '3267101439']]);
        $this->managerHas([
            ['id' => '3460855874', 'name' => 'knowledgedomain'],
            ['id' => '3267101439', 'name' => '3DayBlinds'],
        ]);

        $this->campaign();

        $this->assertTrue(app(GoogleRules::class)->accountChoiceExists());

        app(ListAdAccounts::class)->handle(new Request(['platform' => 'google']));

        $offer = collect(app(Choices::class)->all())->firstWhere('field', 'ad_account_id');

        $this->assertNotNull($offer, 'the account question never reached the screen');
        $this->assertSame(
            ['3460855874', '3267101439'],
            array_column($offer['options'], 'value'),
        );

        // Named, not just numbered: a ten-digit id is not a thing anyone picks.
        $this->assertStringContainsString('knowledgedomain', $offer['options'][0]['label']);
        $this->assertStringContainsString('3460855874', $offer['options'][0]['label']);
    }

    /**
     * One account is not a choice, and must not be dressed as one.
     *
     * This is the state the reporting buyer was in, and the absence of the
     * question was correct there. What was wrong was that it would have stayed
     * absent after an administrator permitted a second account.
     */
    public function test_one_permitted_account_is_recorded_rather_than_asked(): void
    {
        config(['platforms.guardrails.allowed_ad_accounts' => ['3460855874']]);
        $this->managerHas([
            ['id' => '3460855874', 'name' => 'knowledgedomain'],
            ['id' => '3267101439', 'name' => '3DayBlinds'],
        ]);

        $campaign = $this->campaign();

        $this->assertFalse(app(GoogleRules::class)->accountChoiceExists());

        app(ListAdAccounts::class)->handle(new Request(['platform' => 'google']));

        $this->assertNull(
            collect(app(Choices::class)->all())->firstWhere('field', 'ad_account_id'),
            'a question with one answer was put on screen',
        );
        $this->assertSame('3460855874', $campaign->fresh()->ad_account_id);
    }

    /** An account the allow list does not cover is not offered. */
    public function test_an_unpermitted_account_is_not_offered(): void
    {
        config(['platforms.guardrails.allowed_ad_accounts' => ['3460855874', '3267101439']]);
        $this->managerHas([
            ['id' => '3460855874', 'name' => 'knowledgedomain'],
            ['id' => '3267101439', 'name' => '3DayBlinds'],
            ['id' => '7553633821', 'name' => 'BlockAds'],
        ]);

        $this->campaign();

        app(ListAdAccounts::class)->handle(new Request(['platform' => 'google']));

        $offer = collect(app(Choices::class)->all())->firstWhere('field', 'ad_account_id');

        $this->assertNotNull($offer);
        $this->assertNotContains('7553633821', array_column($offer['options'], 'value'));
    }
}
