<?php

namespace Tests\Feature;

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

/**
 * Image creatives are used, or the buyer is told why not.
 *
 * The publisher matched on exact pixels, 1200x628 and 1200x1200, and dropped
 * everything else without a word. Those are Google's recommended sizes; its
 * requirements are 600x314 and 300x300, and the ratio is the part that has to
 * be right. So a perfectly good 1920x1005 landscape was discarded, both slots
 * came out empty, and Google refused the ad afterwards with an error naming no
 * field - after the campaign and the budget had already been created and had
 * to be rolled back.
 *
 * The old comment described exactly the right intent, "sending a near miss
 * trades a clear refusal here for an opaque one from the API after the campaign
 * and budget already exist", and the code did the opposite of it.
 *
 * Portrait is accepted by the chat for Google and had nowhere to go at all.
 * Performance Max has a portrait slot; a responsive display ad does not, so
 * there a 4:5 image is genuinely unusable rather than merely unused.
 */
class GoogleImageCreativesAreNotSilentlyDroppedTest 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]]];

        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*assets:mutate' => Http::response($resource('customers/1234567890/assets/555')),
            '*campaignBudgets:mutate' => Http::response($resource('customers/1234567890/campaignBudgets/111')),
            '*campaigns:mutate' => Http::response($resource('customers/1234567890/campaigns/222')),
            '*adGroups:mutate' => Http::response($resource('customers/1234567890/adGroups/333')),
            '*adGroupAds:mutate' => Http::response($resource('customers/1234567890/adGroupAds/333~444')),
            '*assetGroups:mutate' => Http::response($resource('customers/1234567890/assetGroups/666')),
            '*assetGroupAssets:mutate' => Http::response(['results' => []]),
            '*:mutate' => Http::response(['results' => []]),
            '*googleAds:searchStream' => Http::response([['results' => []]]),
        ]);
    }

    /** @param list<array{0:string,1:int,2:int}> $images */
    private function campaign(string $type, array $images): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Knowledgedom',
            'platform' => 'google',
            'status' => 'draft',
            'campaign_type' => $type,
            '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', 'Browse faster on every site.'],
            ['Browse Faster Today', 'Stop trackers and pop ups.'],
            ['Private Browsing Made Easy', 'Browse faster everywhere.'],
        ] as $index => [$headline, $description]) {
            CampaignAd::create([
                'campaign_id' => $campaign->id,
                'asset_id' => isset($images[$index]) ? $this->image(...$images[$index])->id : null,
                'headline' => $headline,
                'description' => $description,
                'primary_text' => $description,
                'cta' => 'LEARN_MORE',
                'status' => 'draft',
            ]);
        }

        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): array
    {
        $created = [];

        try {
            app(GooglePublisher::class)->create($campaign, 'tester', $created);

            return ['ok' => true, 'error' => null];
        } catch (RuntimeException $e) {
            return ['ok' => false, 'error' => $e->getMessage()];
        }
    }

    /** @return list<array<string,mixed>> every asset create sent */
    private function uploaded(): array
    {
        $sent = [];

        foreach (Http::recorded() as [$request]) {
            if (str_contains($request->url(), '/assets:mutate')) {
                $sent[] = (array) data_get($request->data(), 'operations.0.create', []);
            }
        }

        return $sent;
    }

    // ------------------------------------------------- the images that were lost

    /**
     * The defect: a correctly proportioned image at another resolution.
     *
     * 1920x1005 is 1.91:1 and well over Google's minimum. It was dropped for
     * not being exactly 1200x628.
     */
    public function test_a_landscape_image_at_another_resolution_is_used(): void
    {
        $campaign = $this->campaign('display', [
            ['wide.png', 1920, 1005],
            ['square.png', 1080, 1080],
        ]);

        $result = $this->publish($campaign);

        $this->assertTrue($result['ok'], (string) $result['error']);
        $this->assertCount(2, $this->uploaded());
    }

    /** Google's actual minimum, which is far below its recommendation. */
    public function test_an_image_at_googles_minimum_is_used(): void
    {
        $campaign = $this->campaign('display', [
            ['small-wide.png', 600, 314],
            ['small-square.png', 300, 300],
        ]);

        $this->assertTrue($this->publish($campaign)['ok']);
        $this->assertCount(2, $this->uploaded());
    }

    // ------------------------------------------------------- what is refused

    /**
     * Nothing is created when the shapes are missing.
     *
     * Refused before the campaign and budget exist, which is what the old
     * comment said it was doing and was not.
     */
    public function test_a_campaign_with_no_usable_image_is_refused_before_anything_is_created(): void
    {
        $campaign = $this->campaign('display', [['portrait.png', 1080, 1350]]);

        $result = $this->publish($campaign);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('needs an image 1.91:1 at 600x314 or larger', $result['error']);

        $created = collect(Http::recorded())
            ->contains(fn (array $pair): bool => str_contains($pair[0]->url(), '/campaigns:mutate'));

        $this->assertFalse($created, 'a campaign was created before the images were checked');
    }

    /** And the refusal says what was attached, so it can be acted on. */
    public function test_the_refusal_names_what_was_attached_and_why_it_did_not_fit(): void
    {
        $campaign = $this->campaign('display', [['tiny.png', 400, 209]]);

        $result = $this->publish($campaign);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('tiny.png is 400x209', $result['error']);
        $this->assertStringContainsString('below Google\'s minimum of 600x314', $result['error']);
    }

    /** An image that is no shape Google takes is named as that. */
    public function test_an_image_of_no_usable_shape_is_named(): void
    {
        $campaign = $this->campaign('display', [['banner.png', 1600, 400]]);

        $result = $this->publish($campaign);

        $this->assertStringContainsString('banner.png is 1600x400', $result['error']);
        $this->assertStringContainsString('none of the shapes Google takes', $result['error']);
    }

    /** With nothing attached at all it says so rather than listing nothing. */
    public function test_no_creative_at_all_is_said_plainly(): void
    {
        $campaign = $this->campaign('display', []);

        $this->assertStringContainsString('No image creative is attached', $this->publish($campaign)['error']);
    }

    /**
     * 16:9 is the near miss most likely to be attached by mistake.
     *
     * Seven per cent off 1.91:1, so the tolerance has to exclude it or Google
     * refuses the ad after the campaign exists.
     */
    public function test_sixteen_by_nine_is_not_passed_off_as_landscape(): void
    {
        $campaign = $this->campaign('display', [
            ['wide169.png', 1920, 1080],
            ['square.png', 1080, 1080],
        ]);

        $result = $this->publish($campaign);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('1.91:1', $result['error']);
    }

    // ------------------------------------------------------------- portrait

    /** Performance Max has a portrait slot, so a 4:5 image reaches it. */
    public function test_performance_max_sends_a_portrait_image(): void
    {
        $campaign = $this->campaign('performance_max', [
            ['wide.png', 1200, 628],
            ['square.png', 1200, 1200],
            ['portrait.png', 960, 1200],
        ]);

        // Performance Max will not publish without a logo, which is its own
        // refusal and tested separately.
        $campaign->update(['meta' => ['google_logo_asset_id' => $this->image('logo.png', 512, 512)->id]]);

        $this->assertTrue($this->publish($campaign->fresh())['ok']);

        $fields = collect(Http::recorded())
            ->filter(fn (array $pair): bool => str_contains($pair[0]->url(), '/assetGroupAssets:mutate'))
            ->flatMap(fn (array $pair): array => (array) ($pair[0]->data()['operations'] ?? []))
            ->map(fn (array $operation): mixed => $operation['create']['fieldType'] ?? null)
            ->all();

        $this->assertContains('PORTRAIT_MARKETING_IMAGE', $fields);
    }

    /**
     * Display has no portrait field, so one is not sent there.
     *
     * Sending it would be refused by Google; dropping it quietly is what this
     * change is about, so the campaign still publishes and the image simply
     * has nowhere to go on this type.
     */
    public function test_display_does_not_send_a_portrait_image(): void
    {
        $campaign = $this->campaign('display', [
            ['wide.png', 1200, 628],
            ['square.png', 1200, 1200],
            ['portrait.png', 960, 1200],
        ]);

        $this->assertTrue($this->publish($campaign)['ok']);
        $this->assertCount(2, $this->uploaded(), 'a portrait image was uploaded for a type with no slot for it');
    }

    // ------------------------------------------------------------- read once

    /** Each file is measured once, not once per shape. */
    public function test_each_image_is_read_once(): void
    {
        $campaign = $this->campaign('display', [
            ['wide.png', 1200, 628],
            ['square.png', 1200, 1200],
        ]);

        $this->publish($campaign);

        $this->assertCount(2, $this->uploaded(), 'an image was uploaded more than once');
    }

    /** Search needs no images at all and is unaffected. */
    public function test_a_search_campaign_is_not_asked_for_images(): void
    {
        $campaign = $this->campaign('search', []);

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