<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\PendingChanges;
use App\Models\Asset;
use App\Models\AssetPlatformRef;
use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\Decision;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * Ads written after a campaign went live can now reach it.
 *
 * Publishing created every ad a campaign had, and that was the only moment one
 * ever could be created. An ad written the next day left a draft row that
 * nothing would ever send: the publisher refuses a second publish outright -
 * correctly, because that made a whole second campaign - and no other path
 * created ads. So the work looked finished in the chat and was not on Meta at
 * all, which is the worst of the three possible outcomes because nobody is
 * prompted to check.
 *
 * What these pin: the new ads go into the right ad set on the live campaign, they
 * arrive paused while the campaign spends, the ads already running are untouched,
 * the ones already published are not sent twice, and the pending-changes
 * fingerprint moves so they do not read as an unsent edit for ever.
 */
class AddingAdsToALiveCampaignTest extends TestCase
{
    use RefreshDatabase;

    private Campaign $campaign;

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

        config(['platforms.meta.mcp.enabled' => false]);

        $this->actingAs(User::factory()->create());

        $workspace = app(Workspace::class);
        $workspace->bindTo('conv-add-ads');
        $workspace->ownedBy(auth()->user());

        config([
            'platforms.guardrails.allowed_ad_accounts' => ['act_111'],
            'platforms.guardrails.max_daily_budget' => 500,
            'platforms.guardrails.max_ads_per_publish' => 5,
        ]);

        $this->campaign = $this->liveCampaign();
    }

    private function liveCampaign(): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'published',
            'objective' => 'OUTCOME_TRAFFIC',
            'currency' => 'USD',
            'budget' => 20,
            'budget_mode' => 'daily',
            'budget_level' => 'adset',
            'ad_account_id' => 'act_111',
            'page_id' => 'page-1',
            'landing_url' => 'https://example.com/offer',
            'locations' => ['countries' => ['US']],
            'placements' => ['facebook'],
            'external_campaign_id' => '120111',
            'external_ids' => ['campaign_id' => '120111', 'adset_id' => '120222'],
        ]);

        $campaign->primaryAdSet->update(['external_adset_id' => '120222', 'status' => 'published']);

        // One ad already live, as a published campaign has.
        $campaign->ads()->create([
            'ad_set_id' => $campaign->primaryAdSet->id,
            'headline' => 'Already running',
            'primary_text' => 'The first ad.',
            'cta' => 'SHOP_NOW',
            'asset_id' => $this->asset()->id,
            'external_ad_id' => 'ad-1',
            'external_creative_id' => 'creative-1',
            'status' => 'published',
        ]);

        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign);

        return $campaign->fresh();
    }

    private function asset(): Asset
    {
        $asset = Asset::create([
            'owner_type' => (new User)->getMorphClass(),
            'owner_id' => auth()->id(),
            'kind' => 'image', 'source' => 'generated', 'disk' => 'public',
            'path' => 'creatives/'.uniqid().'.png', 'original_name' => 'x.png',
            'mime' => 'image/png', 'bytes' => 10, 'checksum' => uniqid(),
        ]);

        AssetPlatformRef::create([
            'asset_id' => $asset->id, 'platform' => 'meta',
            'ad_account_id' => 'act_111', 'external_hash' => 'HASH'.$asset->id,
        ]);

        return $asset;
    }

    /** An ad written in the chat after the campaign went live: no platform id. */
    private function draftAd(string $headline, array $attributes = []): CampaignAd
    {
        return $this->campaign->ads()->create([
            'ad_set_id' => $this->campaign->primaryAdSet->id,
            'headline' => $headline,
            'primary_text' => 'Written later.',
            'cta' => 'SHOP_NOW',
            'asset_id' => $this->asset()->id,
            'status' => 'draft',
            ...$attributes,
        ]);
    }

    /** @return array<string, mixed> */
    private function addAds(array $arguments = []): array
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t) => $t->name() === 'campaign__add_ads');

        $this->assertNotNull($tool, 'add_ads is not registered.');

        return json_decode((string) $tool->handle(new Request($arguments)), true);
    }

    private function fakeMeta(): void
    {
        Http::fake([
            '*' => Http::sequence()
                ->push(['id' => 'creative-2'])
                ->push(['id' => 'ad-2'])
                ->push(['id' => 'creative-3'])
                ->push(['id' => 'ad-3'])
                ->whenEmpty(Http::response(['success' => true])),
        ]);
    }

    public function test_it_sends_the_ads_that_were_waiting(): void
    {
        $waiting = $this->draftAd('Written later');
        $this->fakeMeta();

        $result = $this->addAds();

        $this->assertTrue($result['ok'] ?? false, $result['error'] ?? '');
        $this->assertSame('ad-2', $waiting->fresh()->external_ad_id);
        $this->assertSame('creative-2', $waiting->fresh()->external_creative_id);
        $this->assertSame('published', $waiting->fresh()->status);
    }

    /** Into the ad set that is already on the platform, not a new one. */
    public function test_they_go_into_the_existing_ad_set(): void
    {
        $this->draftAd('Written later');
        $this->fakeMeta();

        $this->addAds();

        $bodies = collect(Http::recorded())->map(fn (array $pair): string => (string) $pair[0]->body());

        $this->assertTrue(
            $bodies->contains(fn (string $body): bool => str_contains($body, '120222')),
            'the new ad was not attached to the live ad set',
        );

        // And no ad set was created.
        $urls = collect(Http::recorded())->map(fn (array $pair): string => $pair[0]->url());

        $this->assertFalse(
            $urls->contains(fn (string $url): bool => str_contains($url, 'adsets')),
            'an ad set was created when only ads were being added',
        );
    }

    /** Paused, while the campaign above them is spending. */
    public function test_the_new_ads_arrive_paused(): void
    {
        $this->draftAd('Written later');
        $this->fakeMeta();

        $this->addAds();

        $sent = collect(Http::recorded())
            ->map(fn (array $pair): string => (string) $pair[0]->body())
            ->implode("\n");

        $this->assertStringContainsString('PAUSED', $sent, 'nothing asked for PAUSED');
        $this->assertStringNotContainsString('"status":"ACTIVE"', $sent);
    }

    /**
     * The ad already running is neither re-sent nor changed.
     *
     * Meta treats a creative as immutable, so re-sending a published ad would
     * build a second creative and a second ad for copy that is already live -
     * paying twice to show the same thing.
     */
    public function test_the_ads_already_published_are_left_alone(): void
    {
        $live = $this->campaign->ads()->whereNotNull('external_ad_id')->sole();
        $this->draftAd('Written later');
        $this->fakeMeta();

        $this->addAds();

        $this->assertSame('ad-1', $live->fresh()->external_ad_id, 'the running ad was re-sent');
        $this->assertSame('creative-1', $live->fresh()->external_creative_id);
        $this->assertSame(2, $this->campaign->ads()->count(), 'an extra ad row appeared');
    }

    /** Numbered on from what is there, so Ads Manager reads sensibly. */
    public function test_the_new_ad_is_numbered_after_the_existing_ones(): void
    {
        $this->draftAd('Written later');
        $this->fakeMeta();

        $this->addAds();

        // Decoded: these bodies are form-encoded, so a name reads as "ad+2".
        $sent = collect(Http::recorded())
            ->map(fn (array $pair): string => urldecode((string) $pair[0]->body()))
            ->implode("\n");

        $this->assertStringContainsString('ad 2', $sent, 'the second ad was named as if it were the first');
        $this->assertStringNotContainsString('Winter Sale - ad 1', $sent, 'it reused the first ad\'s name');
    }

    /** Recorded as its own decision, like publishing and starting. */
    public function test_it_is_recorded_as_a_decision(): void
    {
        $this->draftAd('Written later');
        $this->fakeMeta();

        $this->addAds();

        $decision = Decision::where('action', 'add_ads')->first();

        $this->assertNotNull($decision, 'nothing was recorded');
        $this->assertSame('applied', $decision->state);
    }

    /**
     * The published-state fingerprint moves with them.
     *
     * PendingChanges compares a hash of every ad's words and image against what
     * was last sent. Adding ads without moving it leaves the campaign reporting
     * "ad copy or creative changed" for ever, and a buyer told to rebuild ads
     * that are already live.
     */
    public function test_the_pending_changes_fingerprint_moves(): void
    {
        $this->draftAd('Written later');
        $this->fakeMeta();

        $this->assertNotEmpty(
            app(PendingChanges::class)->requiringRebuild($this->campaign->fresh()),
            'precondition: a written-but-unsent ad reads as a pending rebuild',
        );

        $this->addAds();

        $this->assertEmpty(
            app(PendingChanges::class)->requiringRebuild($this->campaign->fresh()),
            'the ads were added but still read as an unsent change',
        );
    }

    /** Nothing waiting is said plainly rather than reported as a success. */
    public function test_nothing_waiting_is_refused(): void
    {
        $this->fakeMeta();

        $result = $this->addAds();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('already on the platform', $result['error']);
        Http::assertNothingSent();
    }

    /** An unpublished campaign is told its ads go out with it. */
    public function test_an_unpublished_campaign_is_refused(): void
    {
        $draft = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Draft', 'platform' => 'meta', 'status' => 'draft', 'currency' => 'USD',
        ]);

        app(Workspace::class)->focusOn($draft);
        $this->fakeMeta();

        $result = $this->addAds();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('has not been published', $result['error']);
        Http::assertNothingSent();
    }

    /** An ad with no copy is refused, by the same rules publishing uses. */
    public function test_an_incomplete_ad_is_refused(): void
    {
        $this->draftAd('Written later', ['headline' => '']);
        $this->fakeMeta();

        $result = $this->addAds();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('headline missing', $result['error']);
        Http::assertNothingSent();
    }

    /**
     * The per-approval limit counts only what is being added.
     *
     * It guards how much one approval may create. Counting the ads already on
     * the campaign as well would make the limit fall as a campaign grew, until
     * a campaign with five ads could never have a sixth.
     */
    public function test_the_limit_counts_only_the_new_ads(): void
    {
        config(['platforms.guardrails.max_ads_per_publish' => 2]);

        // Two to add, against one already live: three in total, over the limit
        // if the existing one were counted.
        $this->draftAd('Second');
        $this->draftAd('Third');
        $this->fakeMeta();

        $result = $this->addAds();

        $this->assertTrue($result['ok'] ?? false, $result['error'] ?? '');
        $this->assertCount(2, $result['added']);
    }

    /** And it still refuses more than the limit in one go. */
    public function test_more_than_the_limit_at_once_is_refused(): void
    {
        config(['platforms.guardrails.max_ads_per_publish' => 2]);

        $this->draftAd('Second');
        $this->draftAd('Third');
        $this->draftAd('Fourth');
        $this->fakeMeta();

        $result = $this->addAds();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('at most 2', $result['error']);
        Http::assertNothingSent();
    }

    /**
     * An ad written for a second ad set is published into that ad set.
     *
     * The case where items 9 and 10 meet, and the one that was passing for the
     * wrong reason: ad_set_id was missing from CampaignAd's fillable list, so
     * every ad was created with a null ad set and matched only because null is
     * read as the first one. A second ad set could never have received an ad.
     */
    public function test_an_ad_written_for_a_second_ad_set_goes_into_that_ad_set(): void
    {
        $second = $this->campaign->adSets()->create([
            'position' => 2,
            'name' => 'UK test',
            'locations' => ['countries' => ['GB']],
            'external_adset_id' => 'adset-2',
            'status' => 'published',
        ]);

        $forSecond = $this->draftAd('For the UK', ['ad_set_id' => $second->id]);

        $this->assertSame($second->id, $forSecond->fresh()->ad_set_id, 'the ad set was not stored');

        $this->fakeMeta();

        $result = $this->addAds(['ad_set_id' => $second->id]);

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

        $bodies = collect(Http::recorded())->map(fn (array $pair): string => (string) $pair[0]->body());

        $this->assertTrue(
            $bodies->contains(fn (string $body): bool => str_contains($body, 'adset-2')),
            'the ad was not attached to the second ad set',
        );
        $this->assertFalse(
            $bodies->contains(fn (string $body): bool => str_contains($body, '120222')),
            'the ad went into the first ad set instead',
        );
    }

    /** And the first ad set's own drafts are not swept in with it. */
    public function test_adding_to_one_ad_set_leaves_the_other_ad_sets_drafts_alone(): void
    {
        $second = $this->campaign->adSets()->create([
            'position' => 2,
            'name' => 'UK test',
            'external_adset_id' => 'adset-2',
            'status' => 'published',
        ]);

        $forFirst = $this->draftAd('For the first');
        $this->draftAd('For the UK', ['ad_set_id' => $second->id]);

        $this->fakeMeta();

        $result = $this->addAds(['ad_set_id' => $second->id]);

        $this->assertTrue($result['ok'] ?? false, $result['error'] ?? '');
        $this->assertCount(1, $result['added'], 'it published more than the ad set it was asked about');
        $this->assertNull($forFirst->fresh()->external_ad_id, 'the first ad set\'s draft was published too');
    }

    /**
     * An ad set id from another campaign is refused, not redirected.
     *
     * The one thing worse than failing to add an ad is adding it to an audience
     * nobody chose.
     */
    public function test_an_ad_set_from_another_campaign_is_refused(): void
    {
        $other = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Someone else', 'platform' => 'meta', 'status' => 'draft', 'currency' => 'USD',
        ]);

        $this->draftAd('Written later');
        $this->fakeMeta();

        $result = $this->addAds(['ad_set_id' => $other->primaryAdSet->id]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('not part of this campaign', $result['error']);
        Http::assertNothingSent();
    }
}
