<?php

namespace Tests\Feature;

use App\Agent\Tools\Campaign\ChoosePixel;
use App\Agent\Workspace;
use App\Campaigns\LaunchFlow;
use App\Campaigns\Platforms\Platforms;
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;

/**
 * "All the conversion events are still missing."
 *
 * Reported after the goals fix was deployed and working: his last two
 * campaigns have every category he picked switched on at Google. What was
 * missing is on this side of it - the campaign panel, which is what he is
 * looking at while he chats.
 *
 * The panel's conversion row read meta.pixel.name, which is Meta's key. Google
 * writes meta.conversion_action, so the row fell through to pixel_id and
 * showed "customers/2099157735/conversionActions/7648890715" - one opaque
 * resource name where he had chosen four events by name, and no sign of the
 * other three anywhere.
 *
 * So the names of every chosen action are kept, not only the primary's, and
 * the panel reads the key its own platform writes.
 */
class ThePanelNamesEveryConversionActionTest extends TestCase
{
    use RefreshDatabase;

    private const ACCOUNT = '2099157735';

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

        config([
            'platforms.guardrails.paused' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['google:'.self::ACCOUNT],
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '346-085-5874',
        ]);

        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*googleAds:searchStream' => Http::response([['results' => [
                ['conversionAction' => [
                    'resourceName' => 'customers/'.self::ACCOUNT.'/conversionActions/7648890715',
                    'name' => 'Subscription Done', 'category' => 'PURCHASE', 'type' => 'WEBPAGE',
                ]],
                ['conversionAction' => [
                    'resourceName' => 'customers/'.self::ACCOUNT.'/conversionActions/7648536689',
                    'name' => 'Continue-General Info', 'category' => 'SUBMIT_LEAD_FORM', 'type' => 'WEBPAGE',
                ]],
                ['conversionAction' => [
                    'resourceName' => 'customers/'.self::ACCOUNT.'/conversionActions/7598350940',
                    'name' => 'Begin checkout', 'category' => 'BEGIN_CHECKOUT', 'type' => 'WEBPAGE',
                ]],
                ['conversionAction' => [
                    'resourceName' => 'customers/'.self::ACCOUNT.'/conversionActions/7598350937',
                    'name' => 'Subscribe', 'category' => 'SUBSCRIBE_PAID', 'type' => 'WEBPAGE',
                ]],
            ]]]),
        ]);
    }

    /** His four, chosen the way the screen sends them. */
    private function campaignWithFourActions(): Campaign
    {
        $user = User::factory()->create();
        $this->actingAs($user);

        $campaign = Campaign::create([
            'user_id' => $user->getKey(),
            'name' => 'stockprices-trade-smarter',
            'platform' => 'google',
            'campaign_type' => 'display',
            'status' => 'draft',
            'ad_account_id' => self::ACCOUNT,
            'objective' => 'SALES',
            'landing_url' => 'https://stockprices.com/landing',
        ]);

        app(Workspace::class)->bindTo('panel-conversions');
        app(Workspace::class)->focusOn($campaign);

        app(ChoosePixel::class)->handle(new Request([
            'pixel_id' => 'customers/'.self::ACCOUNT.'/conversionActions/7648890715',
            'also_count' => [
                'customers/'.self::ACCOUNT.'/conversionActions/7648536689',
                'customers/'.self::ACCOUNT.'/conversionActions/7598350940',
                'customers/'.self::ACCOUNT.'/conversionActions/7598350937',
            ],
        ]));

        return $campaign->fresh();
    }

    /** Every chosen action's name is kept, not only the primary's. */
    public function test_the_names_of_all_four_are_recorded(): void
    {
        $campaign = $this->campaignWithFourActions();

        $this->assertSame(
            ['Subscription Done', 'Continue-General Info', 'Begin checkout', 'Subscribe'],
            array_column((array) data_get($campaign->meta, 'google_conversion_action_names'), 'name'),
        );
    }

    /** The ids stay as they were, because the publisher reads them. */
    public function test_the_ids_are_unchanged(): void
    {
        $campaign = $this->campaignWithFourActions();

        $this->assertCount(4, (array) data_get($campaign->meta, 'google_conversion_actions'));
        $this->assertSame(
            'customers/'.self::ACCOUNT.'/conversionActions/7648890715',
            $campaign->pixel_id,
        );
    }

    /** The panel names them rather than printing a resource name. */
    public function test_the_panel_shows_the_names(): void
    {
        $campaign = $this->campaignWithFourActions();

        $panel = view('partials.campaign-panel', $this->panelData($campaign))->render();

        $this->assertStringContainsString('Subscription Done', $panel);
        $this->assertStringContainsString('Subscribe', $panel);
        $this->assertStringContainsString('Begin checkout', $panel);
        $this->assertStringContainsString('Continue-General Info', $panel);
    }

    /** And the opaque resource name is not what he reads. */
    public function test_the_panel_does_not_show_a_bare_resource_name(): void
    {
        $campaign = $this->campaignWithFourActions();

        $panel = view('partials.campaign-panel', $this->panelData($campaign))->render();

        $this->assertStringNotContainsString('conversionActions/7648890715', $panel);
    }

    /** @return array<string,mixed> */
    private function panelData(Campaign $campaign): array
    {
        return [
            'campaign' => $campaign,
            'previewIdentities' => [],
            'workingOn' => null,
            'rules' => app(Platforms::class)->for($campaign),
            'progress' => app(LaunchFlow::class)->progress($campaign),
            'nextStep' => app(LaunchFlow::class)->next($campaign),
            'blocking' => [],
            'sources' => [],
            'pending' => [],
            'needsRebuild' => [],
            'campaigns' => collect([$campaign]),
            'assets' => collect(),
        ];
    }
}
