<?php

namespace Tests\Feature;

use App\Agent\Instructions;
use App\Agent\Workspace;
use App\Http\Controllers\ChatController;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use ReflectionMethod;
use Tests\TestCase;

/**
 * Seven fields moved off the campaigns table and four things stopped seeing them.
 *
 * locations, audience, placements, optimization_goal, conversion_event, starts_at
 * and ends_at now live on campaign_ad_sets, and Campaign delegates them through
 * HasAdSets; landing_url, budget and budget_mode can also be answered by the
 * brief. Anything that read the row directly went blind, and three readers did:
 *
 *   Instructions::summarise()      attributesToArray()
 *   ChatController::howFarItGot()  campaigns.updated_at
 *   ChatController::footprint()    campaigns.updated_at
 *
 * The symptoms were not subtle. CURRENTLY IN FOCUS showed a campaign with no
 * targeting, no placements, no schedule and - on an unsplit brief - no landing
 * page and no budget, so the model re-asked settled questions while NEXT STEP,
 * which reads through the accessors, said those steps were done. A turn that set
 * the schedule and the targeting and then hit a provider error told the buyer
 * "Nothing in the campaign was changed". And because the footprint also never
 * moved, a 429 on such a turn replayed it and re-ran every tool it had already
 * run - the thing the footprint exists to prevent.
 *
 * The fourth reader, PublishedLocationChangePlanner::preview()'s fingerprint, is
 * fixed the same way and is not covered here: reaching it needs a published
 * campaign plus a provider readback that matches. The change mirrors
 * CampaignApprovalBinding::fingerprint(), which already hashes the ad sets and is
 * tested, and the asymmetry between the two was how the omission was found.
 */
class ThePromptStillSeesWhatMovedOffTheCampaignTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

    private Campaign $campaign;

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

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

        $brief = Brief::create([
            'user_id' => $this->user->id,
            'conversation_id' => 'conv-moved-fields',
            // Answered on the brief and never copied onto the campaign, which is
            // the ordinary single-platform case.
            'landing_url' => 'https://webcrawlers.com/pricing',
            'budget' => 45,
            'budget_mode' => 'daily',
        ]);

        $this->campaign = Campaign::create([
            'user_id' => $this->user->id,
            'brief_id' => $brief->id,
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'draft',
            'currency' => 'USD',
            'ad_account_id' => 'act_111',
            // All ad-set-owned, so none of these land on the campaigns row.
            'locations' => ['countries' => ['US', 'GB']],
            'placements' => ['facebook', 'instagram'],
            'audience' => ['devices' => ['mobile']],
            'optimization_goal' => 'LINK_CLICKS',
            'starts_at' => '2026-11-01 00:00:00',
            'ends_at' => '2026-11-30 00:00:00',
        ]);

        $workspace = app(Workspace::class);
        $workspace->bindTo('conv-moved-fields');
        $workspace->ownedBy($this->user);
        $workspace->produced($this->campaign);
        $workspace->focusOn($this->campaign->fresh());
    }

    // ------------------------------------------------ what the model is told

    /** The row itself holds none of these, which is the point. */
    public function test_the_campaigns_row_really_does_not_hold_them(): void
    {
        $raw = $this->campaign->fresh()->getAttributes();

        foreach (Campaign::OWNED_BY_AD_SET as $field) {
            $this->assertArrayNotHasKey($field, $raw, $field.' is still a campaigns column');
        }
    }

    public function test_the_prompt_shows_ad_set_owned_targeting(): void
    {
        $prompt = app(Instructions::class)->build();

        $this->assertStringContainsString('placements', $prompt);
        $this->assertStringContainsString('facebook', $prompt);
        $this->assertStringContainsString('instagram', $prompt);
        $this->assertStringContainsString('LINK_CLICKS', $prompt, 'the optimisation goal is invisible');
        $this->assertStringContainsString('GB', $prompt, 'the chosen countries are invisible');
    }

    public function test_the_prompt_shows_the_schedule(): void
    {
        $prompt = app(Instructions::class)->build();

        $this->assertStringContainsString('2026-11-01', $prompt);
        $this->assertStringContainsString('2026-11-30', $prompt);
    }

    /** And what the brief answered on the campaign's behalf. */
    public function test_the_prompt_shows_values_inherited_from_the_brief(): void
    {
        $prompt = app(Instructions::class)->build();

        $this->assertStringContainsString('https://webcrawlers.com/pricing', $prompt, 'the landing page is invisible');
        $this->assertStringContainsString('45', $prompt, 'the budget is invisible');
    }

    /** A date must not arrive as a nested Carbon object in the prompt. */
    public function test_dates_are_rendered_as_dates(): void
    {
        $this->assertStringNotContainsString('"date":', app(Instructions::class)->build());
    }

    // ------------------------------- what the turn thinks it changed

    private function campaignState(?Campaign $campaign): ?string
    {
        $method = new ReflectionMethod(ChatController::class, 'campaignState');

        return $method->invoke(app(ChatController::class), $campaign);
    }

    private function footprint(): string
    {
        $method = new ReflectionMethod(ChatController::class, 'footprint');

        return $method->invoke(app(ChatController::class));
    }

    /**
     * Writing only an ad-set-owned field counts as a change.
     *
     * This is the "Nothing in the campaign was changed" lie at its source: the
     * campaigns row is not dirty, so Campaign::save() never updates it.
     */
    public function test_an_ad_set_write_is_seen_as_a_change(): void
    {
        $before = $this->campaignState($this->campaign->fresh());

        $campaign = $this->campaign->fresh();
        $campaign->placements = ['facebook'];
        $campaign->save();

        $this->assertNotSame($before, $this->campaignState($this->campaign->fresh()));
    }

    /** As does adding an ad set, which inserts rather than updating. */
    public function test_adding_an_ad_set_is_seen_as_a_change(): void
    {
        $before = $this->campaignState($this->campaign->fresh());

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

        $this->assertNotSame($before, $this->campaignState($this->campaign->fresh()));
    }

    /** And adding an ad. */
    public function test_adding_an_ad_is_seen_as_a_change(): void
    {
        $before = $this->campaignState($this->campaign->fresh());

        $this->campaign->ads()->create([
            'ad_set_id' => $this->campaign->primaryAdSet->id,
            'headline' => 'Find SEO Opportunities',
            'primary_text' => 'Body copy.',
            'cta' => 'LEARN_MORE',
        ]);

        $this->assertNotSame($before, $this->campaignState($this->campaign->fresh()));
    }

    /** An untouched campaign is still reported as untouched. */
    public function test_doing_nothing_is_not_reported_as_a_change(): void
    {
        $this->assertSame(
            $this->campaignState($this->campaign->fresh()),
            $this->campaignState($this->campaign->fresh()),
        );
    }

    /**
     * The retry footprint moves too, so a 429 does not replay the turn.
     *
     * Same root cause, different consequence: the footprint decides whether a
     * failed turn may be re-run, and a turn whose whole effect was on an ad set
     * looked like it had done nothing at all.
     */
    public function test_the_retry_footprint_moves_when_an_ad_set_is_added(): void
    {
        $before = $this->footprint();

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

        $this->assertNotSame($before, $this->footprint(), 'a 429 would replay the turn and re-run every tool');
    }

    /**
     * And when an existing ad set is merely edited, which counts cannot see.
     *
     * The harder half: no row is inserted, no id changes, and within one second no
     * timestamp moves either. Only measuring the campaign in hand exactly catches
     * it, which is why the footprint carries that as well as the global counts.
     */
    public function test_the_retry_footprint_moves_when_an_ad_set_is_edited(): void
    {
        $before = $this->footprint();

        $campaign = $this->campaign->fresh();
        $campaign->placements = ['instagram'];
        $campaign->save();

        $this->assertNotSame($before, $this->footprint(), 'a 429 would replay the turn and re-run every tool');
    }
}
