<?php

namespace Tests\Feature;

use App\Agent\Choices;
use App\Agent\Tools\Campaign\ChoosePixel;
use App\Agent\Workspace;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * Whose conversion actions are those?
 *
 * Reported: a campaign for stockprices was offered "Purchase" and "Book Demo",
 * which are the two conversion actions on knowledgedomain - the configured
 * account. ChoosePixel read GoogleAdsConnection::shared() and its comment said
 * why: "the same one for everybody here".
 *
 * That was true while the allow list permitted one account. It stopped being
 * true the moment the list was opened and the flow began asking which of the
 * manager's 76 children to buy on, and then this read the wrong account's
 * actions for every campaign. Worse than wrong data: the chosen value is a
 * resource name like customers/3460855874/conversionActions/7486292340, so
 * picking one wrote another account's action onto the campaign.
 *
 * The same assumption was in three more places, which threw "This campaign
 * belongs to a different Google Ads customer" rather than reading the wrong
 * thing - refusing the answer to the question the flow had just asked.
 */
class GoogleReadsTheChosenAccountNotTheConfiguredOneTest extends TestCase
{
    use RefreshDatabase;

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

        config([
            'platforms.guardrails.paused' => false,
            // Both accounts permitted, which is the situation that exposed this.
            'platforms.guardrails.allowed_ad_accounts' => ['google:3460855874', 'google:9876543210'],
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '346-085-5874',
            'services.google_ads.login_customer_id' => '803-900-0543',
        ]);

        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*googleAds:searchStream' => Http::response([[
                'results' => [[
                    'conversionAction' => [
                        'resourceName' => 'customers/9876543210/conversionActions/111',
                        'name' => 'Subscription',
                        'category' => 'SUBSCRIBE_PAID',
                        'type' => 'WEBPAGE',
                    ],
                ]],
            ]]),
        ]);
    }

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

        $campaign = Campaign::create([
            'user_id' => $user->getKey(),
            'name' => 'Conversion actions',
            'platform' => 'google',
            'campaign_type' => 'search',
            'status' => 'draft',
            'ad_account_id' => $accountId,
            'objective' => 'SALES',
            'landing_url' => 'https://stockprices.com/landing',
        ]);

        app(Workspace::class)->bindTo('conversion-actions');
        app(Workspace::class)->focusOn($campaign);

        return $campaign;
    }

    /** Which customer the read was addressed to. */
    private function customersRead(): array
    {
        $customers = [];

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

        return array_values(array_unique($customers));
    }

    public function test_the_actions_are_read_from_the_account_the_campaign_runs_on(): void
    {
        $this->campaignOn('9876543210');

        app(ChoosePixel::class)->handle(new Request([]));

        $this->assertSame(
            ['9876543210'],
            $this->customersRead(),
            'the conversion actions were read from the configured account instead of the campaign\'s',
        );
    }

    /** And the configured account still works, which is the common case. */
    public function test_the_configured_account_is_still_read_when_it_is_the_one_chosen(): void
    {
        $this->campaignOn('3460855874');

        app(ChoosePixel::class)->handle(new Request([]));

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

    /** The options offered belong to that account, so a click cannot cross accounts. */
    public function test_the_offered_resource_names_belong_to_that_account(): void
    {
        $this->campaignOn('9876543210');

        app(ChoosePixel::class)->handle(new Request([]));

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

        $this->assertNotNull($offer);

        foreach ($offer['options'] as $option) {
            $this->assertStringStartsWith('customers/9876543210/', $option['value']);
        }
    }
}
