<?php

namespace Tests\Feature;

use App\Agent\Tools\Campaign\ReviewAssets;
use App\Agent\Workspace;
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 App\Services\Meta\Meta;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * "Creatives 37 and 38 are imported, but neither uploaded."
 *
 * Reported on a Google Display campaign: the upload was refused for
 * act_2099157735, which is the campaign's Google customer id with Meta's
 * prefix on it. review_assets has a LinkedIn branch and an else, and the else
 * is Meta, so a Google campaign's creatives were sent to Graph with a Google
 * account id - an account that is not on Meta's allow list and never will be.
 *
 * Both halves of the report are this one defect. The gate asks whether the
 * creative has reached the platform by looking for an AssetPlatformRef, and
 * the only paths that write one are the Meta and LinkedIn uploads, so a
 * Display or Performance Max publish could not be requested either.
 *
 * Google does not work the way that check assumes. GooglePublisher creates the
 * image assets during publish, from the bytes we hold, deliberately: an asset
 * only needs to exist on the account if a campaign actually uses it. So there
 * is nothing to upload beforehand and nothing for a reference to point at -
 * what readiness means here is that the file is there to send.
 */
class GoogleCreativesAreNotUploadedThroughMetaTest extends TestCase
{
    use RefreshDatabase;

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

        config([
            // Exactly prod: the Google account is permitted, and Meta's list
            // has nothing to do with it.
            'platforms.guardrails.allowed_ad_accounts' => ['google:2099157735'],
        ]);

        Storage::fake('local');
        Storage::disk('local')->put('creatives/images/banner.png', 'image bytes');

        $workspace = app(Workspace::class);
        $workspace->bindTo('google-display-creatives');
        $workspace->ownedBy($user);

        $asset = Asset::create([
            'owner_type' => $user->getMorphClass(),
            'owner_id' => $user->getKey(),
            'kind' => 'image',
            'source' => 'generated',
            'disk' => 'local',
            'path' => 'creatives/images/banner.png',
            'original_name' => 'banner.png',
            'mime' => 'image/png',
            'bytes' => 11,
        ]);
        $workspace->produced($asset, focus: false);

        $campaign = Campaign::create([
            'user_id' => $user->getKey(),
            'name' => 'Display creatives',
            'platform' => 'google',
            'campaign_type' => 'display',
            'status' => 'draft',
            'ad_account_id' => '2099157735',
            'objective' => 'WEBSITE_TRAFFIC',
            'landing_url' => 'https://stockprices.com/landing',
        ]);
        $workspace->produced($campaign);

        CampaignAd::create([
            'campaign_id' => $campaign->getKey(),
            'headline' => 'Live stock prices',
            'primary_text' => 'Track every ticker in real time.',
            'cta' => 'LEARN_MORE',
            'asset_id' => $asset->getKey(),
        ]);

        return $campaign;
    }

    /** A Meta double that fails the test if it is reached at all. */
    private function metaThatMustNotBeCalled(): Meta
    {
        $meta = $this->createMock(Meta::class);
        $meta->method('on')->willReturnSelf();
        $meta->expects($this->never())->method('uploadImage');
        $meta->expects($this->never())->method('uploadVideo');

        return $meta;
    }

    /** The defect in one assertion: Graph is not where a Google creative goes. */
    public function test_a_google_creative_is_not_sent_to_meta(): void
    {
        $this->googleDisplayCampaign();

        $result = json_decode((string) (new ReviewAssets(
            app(Workspace::class),
            $this->metaThatMustNotBeCalled(),
        ))->handle(new Request([])), true);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertArrayNotHasKey('failed', $result);
    }

    /** And it says what will happen instead, rather than reporting an upload. */
    public function test_it_says_the_assets_are_created_at_publish(): void
    {
        $this->googleDisplayCampaign();

        $result = json_decode((string) (new ReviewAssets(
            app(Workspace::class),
            $this->metaThatMustNotBeCalled(),
        ))->handle(new Request([])), true);

        $this->assertArrayNotHasKey('just_uploaded', $result);
        $this->assertSame(1, $result['attached']);
        $this->assertStringContainsString('publish', strtolower((string) ($result['note'] ?? '')));
    }

    /**
     * No Meta-shaped reference is invented for Google.
     *
     * The old else branch wrote the Graph image hash to an AssetPlatformRef
     * row stamped with the campaign's platform, so a successful Meta upload
     * would have recorded a Meta hash as this Google account's asset.
     */
    public function test_no_platform_reference_is_written_for_google(): void
    {
        $campaign = $this->googleDisplayCampaign();

        (new ReviewAssets(app(Workspace::class), $this->metaThatMustNotBeCalled()))->handle(new Request([]));

        $asset = $campaign->ads()->with('asset')->first()->asset;

        $this->assertNull($asset->refFor('google', '2099157735'));
    }

    /** The other half of the report: the publish gate stopped asking for one. */
    public function test_the_publish_gate_does_not_wait_for_an_upload_that_never_happens(): void
    {
        $campaign = $this->googleDisplayCampaign();

        $problems = app(PublishGate::class)->check($campaign->fresh());

        $this->assertSame(
            [],
            array_values(array_filter($problems, static fn (string $problem): bool => str_contains($problem, 'creative not uploaded'))),
        );
    }

    /**
     * It is still refused when the file itself has gone.
     *
     * Dropping the reference check must not drop the check. Google builds the
     * asset from these bytes at publish, so no bytes is a publish that fails
     * after the campaign and the budget exist.
     */
    public function test_a_missing_file_is_still_a_problem(): void
    {
        $campaign = $this->googleDisplayCampaign();

        Storage::disk('local')->delete('creatives/images/banner.png');

        $problems = app(PublishGate::class)->check($campaign->fresh());

        $this->assertNotSame(
            [],
            array_values(array_filter($problems, static fn (string $problem): bool => str_contains($problem, 'creative'))),
            'a Display campaign whose image file is gone was allowed through the gate',
        );
    }

    /** Meta still uploads before publish, which is how Meta works. */
    public function test_meta_still_uploads_before_publish(): void
    {
        $this->assertTrue(app(Platforms::class)->for('meta')->uploadsCreativeBeforePublish());
        $this->assertTrue(app(Platforms::class)->for('linkedin')->uploadsCreativeBeforePublish());
        $this->assertFalse(app(Platforms::class)->for('google')->uploadsCreativeBeforePublish());
    }
}
