<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * Writing new copy must not delete the rows for ads that are live.
 *
 * write_ad_copy replaced every ad on the campaign, which is right while nothing
 * has been published: rewriting before launch should leave one set of ads
 * behind, not two. The focused campaign was kept in the target list even when
 * published - only published siblings were rejected - so on a live campaign the
 * same delete ran against rows carrying external_ad_id.
 *
 * Meta cannot edit a running ad's words. A creative there is immutable, which is
 * why PendingChanges calls a copy change "a new creative and a new ad". So the
 * delete was local only: the ads carried on running and nothing here pointed at
 * them any more - not editable, not pausable, not visible as ours. The same
 * shape as the LinkedIn rollback defect that file already documents.
 *
 * It mattered more once add_ads existed, because the replacements would then be
 * published alongside the orphans rather than simply never sent.
 */
class WritingCopyDoesNotOrphanLiveAdsTest extends TestCase
{
    use RefreshDatabase;

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

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

        $workspace = app(Workspace::class);
        $workspace->bindTo('conv-write-copy');
        $workspace->ownedBy(auth()->user());
    }

    private function campaign(array $attributes = []): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'draft',
            'objective' => 'OUTCOME_TRAFFIC',
            'currency' => 'USD',
            'ad_account_id' => 'act_111',
            'landing_url' => 'https://example.com/offer',
            ...$attributes,
        ]);

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

        return $campaign->fresh();
    }

    private function liveCampaign(): Campaign
    {
        $campaign = $this->campaign([
            'status' => 'published',
            'external_campaign_id' => '120111',
            'external_ids' => ['campaign_id' => '120111', 'adset_id' => '120222'],
        ]);

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

        $campaign->ads()->create([
            'ad_set_id' => $campaign->primaryAdSet->id,
            'headline' => 'Already running',
            'primary_text' => 'The ad that is live.',
            'cta' => 'SHOP_NOW',
            'external_ad_id' => 'ad-1',
            'external_creative_id' => 'creative-1',
            'status' => 'published',
        ]);

        return $campaign->fresh();
    }

    /** @return array<string, mixed> */
    private function write(array $ads, ?int $adSetId = null): array
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t) => $t->name() === 'campaign__write_ad_copy');

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

        return json_decode((string) $tool->handle(new Request(array_filter([
            'ads' => $ads,
            'ad_set_id' => $adSetId,
        ]))), true);
    }

    /** @return array<string, string> */
    private function ad(string $headline): array
    {
        return [
            'headline' => $headline,
            'primary_text' => 'Body copy for '.$headline,
            'cta' => 'SHOP_NOW',
        ];
    }

    // ------------------------------------------------- the ads already live

    /** The defect: the row for a running ad was deleted. */
    public function test_a_live_ad_is_not_deleted(): void
    {
        $campaign = $this->liveCampaign();
        $live = $campaign->ads()->whereNotNull('external_ad_id')->sole();

        $this->write([$this->ad('Brand new')]);

        $this->assertNotNull(
            CampaignAd::find($live->id),
            'the row pointing at a live Meta ad was deleted, so nothing here can reach it any more',
        );
        $this->assertSame('ad-1', $live->fresh()->external_ad_id);
    }

    /** And the new copy is an addition beside it. */
    public function test_the_new_copy_is_added_beside_it(): void
    {
        $campaign = $this->liveCampaign();

        $this->write([$this->ad('Brand new')]);

        $this->assertSame(2, $campaign->ads()->count());
        $this->assertSame(
            'Brand new',
            $campaign->ads()->whereNull('external_ad_id')->sole()->headline,
        );
    }

    /** Said back, so the model does not report the campaign as having one ad. */
    public function test_the_result_says_how_many_are_already_live(): void
    {
        $this->liveCampaign();

        $result = $this->write([$this->ad('Brand new')]);

        $this->assertSame(1, $result['written']['Winter Sale']['already_live'] ?? null);
    }

    /** Rewriting twice still leaves one draft, not two. */
    public function test_rewriting_replaces_the_draft_rather_than_stacking(): void
    {
        $campaign = $this->liveCampaign();

        $this->write([$this->ad('First attempt')]);
        $this->write([$this->ad('Second attempt')]);

        $this->assertSame(2, $campaign->ads()->count(), 'the drafts stacked up');
        $this->assertSame(
            'Second attempt',
            $campaign->ads()->whereNull('external_ad_id')->sole()->headline,
        );
    }

    /** On a draft campaign nothing changes: the set is still replaced. */
    public function test_a_draft_campaign_still_has_its_ads_replaced(): void
    {
        $campaign = $this->campaign();

        $this->write([$this->ad('First'), $this->ad('Second')]);
        $this->write([$this->ad('Only one now')]);

        $this->assertSame(1, $campaign->ads()->count());
        $this->assertSame('Only one now', $campaign->ads()->sole()->headline);
    }

    // ------------------------------------------------------------- ad sets

    /** Copy lands on the campaign's first ad set when none is named. */
    public function test_copy_goes_to_the_first_ad_set_by_default(): void
    {
        $campaign = $this->campaign();

        $this->write([$this->ad('For the first')]);

        $this->assertSame(
            $campaign->primaryAdSet->id,
            $campaign->ads()->sole()->ad_set_id,
            'an ad was written with no ad set, so nothing can place it',
        );
    }

    /**
     * And into a second ad set when one is named.
     *
     * Without this, add_ad_set made an ad set that nothing in the chat could
     * fill: every ad was written to the campaign with no ad set, which reads as
     * the first one.
     */
    public function test_copy_can_be_written_into_a_second_ad_set(): void
    {
        $campaign = $this->campaign();

        $second = $campaign->adSets()->create([
            'position' => 2,
            'name' => 'UK test',
            'locations' => ['countries' => ['GB']],
        ]);

        $this->write([$this->ad('For the UK')], $second->id);

        $this->assertSame($second->id, $campaign->ads()->sole()->ad_set_id);
    }

    /** Rewriting one ad set's copy leaves the other's alone. */
    public function test_writing_for_one_ad_set_does_not_clear_the_other(): void
    {
        $campaign = $this->campaign();

        $second = $campaign->adSets()->create(['position' => 2, 'name' => 'UK test']);

        $this->write([$this->ad('For the first')]);
        $this->write([$this->ad('For the UK')], $second->id);

        $this->assertSame(2, $campaign->ads()->count(), 'the first ad set\'s copy was cleared');
        $this->assertSame(
            'For the first',
            $campaign->ads()->where('ad_set_id', $campaign->primaryAdSet->id)->sole()->headline,
        );
    }

    /** An ad set from a campaign outside this conversation is refused. */
    public function test_an_ad_set_from_another_campaign_is_refused(): void
    {
        $this->campaign();

        $other = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Someone else', 'platform' => 'meta', 'status' => 'draft', 'currency' => 'USD',
        ]);

        $result = $this->write([$this->ad('Wrong place')], $other->primaryAdSet->id);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('does not belong to any campaign', $result['error']);
    }

    /**
     * Naming an ad set on a multi-platform brief writes for every campaign.
     *
     * This writes for every campaign sharing the brief, and an ad set belongs to
     * one of them. Asking each target in turn for the named ad set meant the
     * campaign that owned it had its copy written and the next one refused: a
     * partial write, reported as "that ad set is not part of this campaign"
     * without saying which campaign was meant.
     */
    public function test_naming_an_ad_set_still_writes_for_the_whole_brief(): void
    {
        $brief = Brief::create(['user_id' => auth()->id(), 'conversation_id' => 'conv-write-copy']);

        $meta = $this->campaign(['brief_id' => $brief->id]);
        $google = Campaign::create([
            'user_id' => auth()->id(), 'brief_id' => $brief->id,
            'name' => 'Google side', 'platform' => 'google', 'status' => 'draft', 'currency' => 'USD',
            'landing_url' => 'https://example.com/offer',
        ]);

        $second = $meta->adSets()->create(['position' => 2, 'name' => 'UK test']);

        // Three, because a Google search ad is built from the headlines of all
        // the variations and the rules require at least that many.
        $result = $this->write(
            [$this->ad('One'), $this->ad('Two'), $this->ad('Three')],
            $second->id,
        );

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

        // The named ad set got the Meta copy, and Google used its own first one.
        $this->assertSame(
            [$second->id],
            $meta->ads()->pluck('ad_set_id')->unique()->values()->all(),
        );
        $this->assertSame(
            [$google->primaryAdSet->id],
            $google->ads()->pluck('ad_set_id')->unique()->values()->all(),
        );
    }

    /** And a bad id writes nothing at all, rather than part of the brief. */
    public function test_a_bad_ad_set_id_writes_nothing(): void
    {
        $brief = Brief::create(['user_id' => auth()->id(), 'conversation_id' => 'conv-write-copy']);
        $meta = $this->campaign(['brief_id' => $brief->id]);

        $outsider = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Outsider', 'platform' => 'meta', 'status' => 'draft', 'currency' => 'USD',
        ]);

        $result = $this->write(
            [$this->ad('One'), $this->ad('Two'), $this->ad('Three')],
            $outsider->primaryAdSet->id,
        );

        $this->assertFalse($result['ok']);
        $this->assertSame(0, $meta->ads()->count(), 'copy was written before the refusal');
    }
}
