<?php

namespace Tests\Feature;

use App\Campaigns\Publishing\GooglePublisher;
use App\Models\Asset;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\GoogleAdsConnection;
use App\Models\User;
use App\Services\GoogleAdsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use RuntimeException;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

/**
 * A Performance Max asset group is built out of assets, including its business name.
 *
 * Google requires a business name on an asset group. The Display branch sends
 * one as a field on the ad, and an asset group has no such field - it links one
 * like any other asset - so a Performance Max group was always built without
 * it and Google would refuse the group.
 *
 * Fixing that in isolation was not possible, because the same defect sat under
 * the headlines and descriptions already there. An asset group links resource
 * names; the publisher hands over plain strings, the way a responsive search ad
 * takes them; and the builder put those strings straight into the link's
 * "asset" field. So Google was being sent a headline where it expected
 * customers/<id>/assets/<id>. Adding a business name as raw text would have
 * been a fifth instance of the same bug rather than a fix.
 *
 * The method that would have created them, createTextAsset, is one of several
 * that app/Mcp/Tools/GoogleAds calls and that have never existed.
 */
class APerformanceMaxAssetGroupCarriesItsBusinessNameTest extends TestCase
{
    use RefreshDatabase, SeedsVerifiedCountries;

    private User $user;

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

        $this->seedVerifiedCountries();
        Storage::fake('local');

        $this->user = User::factory()->create();

        config([
            'platforms.guardrails.allowed_ad_accounts' => ['1234567890'],
            'platforms.guardrails.max_daily_budget' => 1000,
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '1234567890',
        ]);

        $resource = fn (string $path): array => ['results' => [['resourceName' => $path]]];
        $asset = 0;

        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            // A distinct id per asset, so a link pointing at the wrong one is
            // visible rather than hidden behind a single shared resource name.
            '*assets:mutate' => function () use (&$asset): mixed {
                $asset++;

                return Http::response(['results' => [['resourceName' => 'customers/1234567890/assets/'.$asset]]]);
            },
            '*campaignBudgets:mutate' => Http::response($resource('customers/1234567890/campaignBudgets/111')),
            '*campaigns:mutate' => Http::response($resource('customers/1234567890/campaigns/222')),
            '*assetGroups:mutate' => Http::response($resource('customers/1234567890/assetGroups/333')),
            '*assetGroupAssets:mutate' => Http::response(['results' => []]),
            '*:mutate' => Http::response(['results' => []]),
            '*googleAds:searchStream' => Http::response([['results' => []]]),
        ]);
    }

    private function campaign(?string $businessName = 'Knowledgedom Insurance'): Campaign
    {
        $brief = Brief::create([
            'user_id' => $this->user->id,
            'landing_url' => 'https://example.com/offer',
            'page_analysis' => array_filter([
                'url' => 'https://example.com/offer',
                'title' => $businessName,
                'brand' => $businessName,
            ]),
        ]);

        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'brief_id' => $brief->id,
            'name' => 'Knowledgedom PMax',
            'platform' => 'google',
            'status' => 'draft',
            'campaign_type' => 'performance_max',
            'ad_account_id' => '1234567890',
            'landing_url' => 'https://example.com/offer',
            'objective' => 'LEADS',
            'budget' => 50,
            'budget_mode' => 'daily',
            'currency' => 'USD',
            'bid_strategy' => 'MAXIMIZE_CONVERSIONS',
            'locations' => ['countries' => ['US']],
            'placements' => ['search'],
            'utm' => '',
        ]);

        foreach ([
            ['Block annoying ads', 'Stop trackers and pop ups.', 'landscape.png', 1200, 628],
            ['Browse faster today', 'Browse faster on every site.', 'square.png', 1200, 1200],
            ['Private browsing made easy', 'Keep your browsing yours.', null, 0, 0],
        ] as [$headline, $description, $file, $width, $height]) {
            CampaignAd::create([
                'campaign_id' => $campaign->id,
                'asset_id' => $file === null ? null : $this->image($file, $width, $height)->id,
                'headline' => $headline,
                'description' => $description,
                'primary_text' => $description,
                'cta' => 'LEARN_MORE',
                'status' => 'draft',
            ]);
        }

        // Google will not run an asset group without a logo, so every PMax
        // campaign here needs one before it can reach the asset group at all.
        $campaign->update(['meta' => ['google_logo_asset_id' => $this->image('logo.png', 512, 512)->id]]);

        return $campaign->fresh();
    }

    private function image(string $name, int $width, int $height): Asset
    {
        $image = imagecreatetruecolor($width, $height);
        ob_start();
        imagepng($image);
        $bytes = (string) ob_get_clean();
        imagedestroy($image);

        Storage::disk('local')->put($name, $bytes);

        return Asset::create([
            'user_id' => $this->user->id,
            'kind' => 'image',
            'disk' => 'local',
            'path' => $name,
            'original_name' => $name,
        ]);
    }

    private function publish(Campaign $campaign): void
    {
        $created = [];
        app(GooglePublisher::class)->create($campaign, 'tester', $created);
    }

    /** @return list<array{fieldType: string, asset: string}> every asset-group link sent */
    private function links(): array
    {
        $links = [];

        foreach (Http::recorded() as [$request]) {
            if (! str_contains($request->url(), '/assetGroupAssets:mutate')) {
                continue;
            }

            foreach ((array) ($request->data()['operations'] ?? []) as $operation) {
                $links[] = [
                    'fieldType' => (string) ($operation['create']['fieldType'] ?? ''),
                    'asset' => (string) ($operation['create']['asset'] ?? ''),
                ];
            }
        }

        return $links;
    }

    /** @return list<string> the text of every text asset created */
    private function textAssets(): array
    {
        $texts = [];

        foreach (Http::recorded() as [$request]) {
            if (! str_contains($request->url(), '/assets:mutate')) {
                continue;
            }

            if (filled($text = data_get($request->data(), 'operations.0.create.textAsset.text'))) {
                $texts[] = (string) $text;
            }
        }

        return $texts;
    }

    // ------------------------------------------------------- the business name

    public function test_the_asset_group_links_a_business_name(): void
    {
        $this->publish($this->campaign());

        $this->assertContains('BUSINESS_NAME', array_column($this->links(), 'fieldType'));
    }

    public function test_the_business_name_is_sent_as_text(): void
    {
        $this->publish($this->campaign());

        $this->assertContains('Knowledgedom Insurance', $this->textAssets());
    }

    /** It is linked as an asset, not sent as a field the asset group does not have. */
    public function test_the_business_name_link_points_at_an_asset(): void
    {
        $this->publish($this->campaign());

        $link = collect($this->links())->firstWhere('fieldType', 'BUSINESS_NAME');

        $this->assertNotNull($link);
        $this->assertStringStartsWith('customers/1234567890/assets/', $link['asset']);
    }

    // ------------------------------------------- the copy it sits alongside

    /**
     * The defect underneath it: copy was linked as raw text.
     *
     * Every link has to point at a resource name. A headline in that field is
     * what Google was being sent.
     */
    public function test_every_link_points_at_a_resource_name(): void
    {
        $this->publish($this->campaign());

        foreach ($this->links() as $link) {
            $this->assertStringStartsWith(
                'customers/1234567890/assets/',
                $link['asset'],
                sprintf('%s was linked to "%s", which is not an asset', $link['fieldType'], $link['asset']),
            );
        }
    }

    public function test_the_headlines_are_created_as_text_assets(): void
    {
        $this->publish($this->campaign());

        $this->assertContains('Block annoying ads', $this->textAssets());
        $this->assertContains('Browse faster today', $this->textAssets());
    }

    public function test_the_descriptions_are_created_as_text_assets(): void
    {
        $this->publish($this->campaign());

        $this->assertContains('Stop trackers and pop ups.', $this->textAssets());
    }

    /** Each line becomes its own asset, so no two links share one by accident. */
    public function test_each_line_gets_its_own_asset(): void
    {
        $this->publish($this->campaign());

        $copyLinks = collect($this->links())
            ->filter(fn (array $link): bool => in_array($link['fieldType'], ['HEADLINE', 'DESCRIPTION', 'LONG_HEADLINE', 'BUSINESS_NAME'], true));

        $this->assertSame(
            $copyLinks->count(),
            $copyLinks->pluck('asset')->unique()->count(),
            'two pieces of copy were linked to the same asset',
        );
    }

    // ------------------------------------------------------------- the edges

    /**
     * An empty line is refused rather than created as a blank asset.
     *
     * Tested against the service directly: the publish path never produces an
     * empty line, so asserting on a published campaign passes whether the
     * guard is there or not.
     */
    public function test_an_empty_line_is_not_created_as_an_asset(): void
    {
        $connection = GoogleAdsConnection::shared();

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('cannot be empty');

        try {
            app(GoogleAdsService::class)->createTextAsset($connection, "   \n ");
        } finally {
            $this->assertSame([], $this->textAssets(), 'a blank text asset was sent to Google');
        }
    }
}
