<?php

namespace Tests\Feature;

use App\Campaigns\Creatives\DisplayImageShapes;
use App\Campaigns\Platforms\Platforms;
use App\Campaigns\PublishGate;
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\Storage;
use Tests\TestCase;

/**
 * "When I tried to launch display campaign, it gave me an error."
 *
 * The gate applied the responsive search ad's copy minimums - three headlines
 * and two descriptions - to every Google campaign whatever channel it ran on,
 * and said "a responsive search ad needs at least 3 different headlines" about
 * a Display campaign. A responsive display ad is a different ad: one headline
 * and one description is a complete one.
 *
 * Found by publishing one. A Display campaign with a single headline and a
 * single description was refused twice by the gate and then accepted by Google
 * on account 346-085-5874, created PAUSED as a RESPONSIVE_DISPLAY_AD and read
 * back before being removed. The floor the gate was enforcing is not Google's.
 *
 * Performance Max keeps the three-and-two floor: its asset groups are held to
 * the higher minimum, and nothing here has published one end to end to say
 * otherwise, so the existing behaviour stands rather than being loosened on a
 * guess.
 */
class ADisplayCampaignIsNotJudgedAsASearchAdTest extends TestCase
{
    use RefreshDatabase;

    private function campaign(string $type, int $headlines, int $descriptions): Campaign
    {
        $user = User::factory()->create();
        $this->actingAs($user);

        $campaign = Campaign::create([
            'user_id' => $user->getKey(),
            'name' => 'Copy floor',
            'platform' => 'google',
            'campaign_type' => $type,
            'status' => 'draft',
            'ad_account_id' => '3460855874',
            'objective' => 'WEBSITE_TRAFFIC',
            'landing_url' => 'https://iblockads.org/extension/landing',
            'budget' => 10,
            'locations' => ['countries' => ['US']],
        ]);

        // One ad per headline, and the descriptions spread across them, which
        // is how the gate counts them: unique values over all of the ads.
        for ($i = 0; $i < max($headlines, $descriptions); $i++) {
            CampaignAd::create([
                'campaign_id' => $campaign->getKey(),
                'headline' => $i < $headlines ? 'Headline number '.($i + 1) : 'Headline number 1',
                'primary_text' => $i < $descriptions ? 'Description number '.($i + 1) : 'Description number 1',
                'cta' => 'LEARN_MORE',
            ]);
        }

        return $campaign->fresh();
    }

    /**
     * Just the copy-floor problems.
     *
     * Matched on "different headline" and "different description", which is
     * the floor rule's own wording. The per-ad "headline missing" checks are a
     * different question, and so is the keyword rule, which also opens with
     * "needs at least".
     *
     * @return list<string>
     */
    private function copyProblems(Campaign $campaign): array
    {
        return array_values(array_filter(
            app(PublishGate::class)->check($campaign),
            static fn (string $problem): bool => str_contains($problem, 'different headline')
                || str_contains($problem, 'different description'),
        ));
    }

    /** The reported case, and the one Google accepted. */
    public function test_one_headline_and_one_description_is_a_complete_display_ad(): void
    {
        $this->assertSame([], $this->copyProblems($this->campaign('display', 1, 1)));
    }

    /** Nothing at all is still not an ad. */
    public function test_a_display_ad_still_needs_a_headline_and_a_description(): void
    {
        $campaign = $this->campaign('display', 1, 1);
        $campaign->ads()->update(['headline' => '', 'primary_text' => '']);

        $this->assertNotSame([], $this->copyProblems($campaign->fresh()));
    }

    /** Search is unchanged: Google refuses the ad outright below three. */
    public function test_search_still_needs_three_headlines(): void
    {
        $problems = $this->copyProblems($this->campaign('search', 2, 2));

        $this->assertCount(1, $problems, implode(' | ', $problems));
        $this->assertStringContainsString('responsive search ad', $problems[0]);
        $this->assertStringContainsString('3 different headlines', $problems[0]);
    }

    /** And two descriptions. */
    public function test_search_still_needs_two_descriptions(): void
    {
        $problems = $this->copyProblems($this->campaign('search', 3, 1));

        $this->assertCount(1, $problems);
        $this->assertStringContainsString('2 different descriptions', $problems[0]);
    }

    /** Performance Max keeps the higher floor. */
    public function test_performance_max_keeps_the_search_floor(): void
    {
        $this->assertNotSame([], $this->copyProblems($this->campaign('performance_max', 1, 1)));
    }

    /** The problem names the ad the buyer is actually building. */
    public function test_a_display_problem_does_not_call_it_a_search_ad(): void
    {
        $campaign = $this->campaign('display', 1, 1);
        $campaign->ads()->update(['headline' => '']);

        foreach ($this->copyProblems($campaign->fresh()) as $problem) {
            $this->assertStringNotContainsString('responsive search ad', $problem);
        }
    }

    /**
     * Google's stated minimum is the gate's rule, not its recommendation.
     *
     * The gate asked for exactly 1200x628 and exactly 1200x1200. Google takes
     * 1.91:1 at 600x314 and 1:1 at 300x300: a 1920x1005 and a 500x500 pair was
     * refused here and then created by Google as a RESPONSIVE_DISPLAY_AD on
     * 346-085-5874. The publisher already sorted creatives this way, so the two
     * disagreed about what a usable creative is.
     */
    public function test_an_on_ratio_image_above_the_minimum_is_usable(): void
    {
        $this->assertTrue(DisplayImageShapes::fits('landscape', 1920, 1005));
        $this->assertTrue(DisplayImageShapes::fits('square', 500, 500));
        $this->assertTrue(DisplayImageShapes::fits('landscape', 1200, 628));
        $this->assertTrue(DisplayImageShapes::fits('square', 1200, 1200));
    }

    /** Below Google's minimum is still refused, and so is the wrong shape. */
    public function test_too_small_or_the_wrong_shape_is_not_usable(): void
    {
        $this->assertFalse(DisplayImageShapes::fits('landscape', 382, 200));
        $this->assertFalse(DisplayImageShapes::fits('square', 299, 299));
        // 9:16, which is what Mohsin's creative 20 was.
        $this->assertFalse(DisplayImageShapes::fits('square', 1080, 1920));
        $this->assertNull(DisplayImageShapes::shapeOf(1080, 1920));
    }

    /** One table, so the gate and the publish cannot disagree. */
    public function test_the_gate_asks_for_what_the_publisher_accepts(): void
    {
        $campaign = $this->campaign('display', 1, 1);

        Storage::fake('local');
        Storage::disk('local')->put('creatives/images/wide.png', $this->png(1920, 1005));
        Storage::disk('local')->put('creatives/images/sq.png', $this->png(500, 500));

        foreach (['wide.png', 'sq.png'] as $file) {
            $asset = Asset::create([
                'owner_type' => (new User)->getMorphClass(),
                'owner_id' => $campaign->user_id,
                'kind' => 'image', 'source' => 'generated', 'disk' => 'local',
                'path' => 'creatives/images/'.$file, 'original_name' => $file,
                'mime' => 'image/png', 'bytes' => 10,
            ]);

            CampaignAd::create([
                'campaign_id' => $campaign->getKey(), 'asset_id' => $asset->getKey(),
                'headline' => 'Headline number 1', 'primary_text' => 'Description number 1',
                'cta' => 'LEARN_MORE',
            ]);
        }

        $imageProblems = array_values(array_filter(
            app(PublishGate::class)->check($campaign->fresh()),
            static fn (string $problem): bool => str_contains($problem, 'image'),
        ));

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

    /** A flat PNG at an exact size, which is all the gate measures. */
    private function png(int $width, int $height): string
    {
        $image = imagecreatetruecolor($width, $height);
        imagefill($image, 0, 0, imagecolorallocate($image, 10, 20, 30));
        ob_start();
        imagepng($image);

        return (string) ob_get_clean();
    }

    /** The floor is the platform's answer, so it is asked of the platform. */
    public function test_the_floor_is_a_rule_of_the_channel(): void
    {
        $rules = app(Platforms::class)->for('google');

        $this->assertSame(['headlines' => 1, 'descriptions' => 1], $rules->copyFloor('display'));
        $this->assertSame(['headlines' => 3, 'descriptions' => 2], $rules->copyFloor('search'));
        $this->assertSame(['headlines' => 3, 'descriptions' => 2], $rules->copyFloor('performance_max'));
    }
}
