<?php

namespace Tests\Feature;

use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use RuntimeException;
use Tests\TestCase;

/**
 * What the targeting revision guard does today, and what it costs.
 *
 * This records behaviour rather than endorsing it, because the behaviour is a
 * deliberate trade-off with a real price and the decision should be visible
 * instead of buried in twelve copies of one `if`.
 *
 * Every mutator on TargetingSelections bumps the targeting revision, and every
 * one refuses an answer whose revision is not exactly current. The chooser carries
 * the revision it was rendered with, so a turn performing two edits from one
 * screen invalidates its own second edit.
 *
 * What that protects: a stale chooser replayed over a newer answer. Pick US, then
 * an older button still on screen submits CA, and without the guard the country
 * silently becomes CA. TargetingSelectionsTest::test_stale_revision_does_not_change_targeting
 * and MetaLocationTargetingTest::test_stale_or_wrong_country_mapping_cannot_be_attached
 * both pin exactly that, so it is intended.
 *
 * What it costs: two edits that *compose* are refused too, and one turn routinely
 * is two edits. On prod on 6 Oct, conversation 01a1115e, the turn was
 *
 *   "Remove Meta include location ID 3886 from US at targeting revision 4.
 *    Target the whole selected countries at targeting revision 4."
 *
 * which is worth being precise about, because it is not something a human typed.
 * The front end composes that sentence from the `sends` strings of the options the
 * buyer clicked (chat.js, and ChooseLocation's own `sends` text), so the product's
 * chooser machinery built a single message carrying two edits stamped with the
 * same revision, handed it to itself, and refused its own second half. Mining the
 * dev corpus showed roughly three quarters of stored user-role messages are
 * generated this way, so this shape is routine rather than a user quirk.
 *
 * The removal succeeded and took the counter with it; the whole-country half was
 * told "Targeting changed since it was opened". They retried at revision 5, then
 * 6, were refused both times, searched again, and were finally told both countries
 * were already targeted in full. Seven turns, four refusals, and the targeting
 * ended exactly where it started, with nobody else editing it.
 *
 * The guard cannot tell a replay from a composition, because an equality check on
 * a counter carries no information about what the caller meant. Two ways out, both
 * real changes to a guard that sits in front of live ad spend, so neither is made
 * here:
 *
 *   1. Measure staleness against the revision the turn opened on rather than the
 *      latest write, making TargetingSelections a scoped binding so a turn is one
 *      request however many tools it calls. Fixes composition; loses replay
 *      protection within a turn, which is what the two tests above defend.
 *   2. Key the allowance on the operation, so repeating the same mutator from one
 *      stamp is still refused while a different one is allowed. Keeps both
 *      properties and costs a little cleverness in the guard.
 *
 * Verified reproducible: option 1 was implemented and reverted on 6 Oct, and it
 * turned both of those tests red, which is how the trade-off was found.
 */
class ASecondTargetingEditInOneTurnIsRefusedTest extends TestCase
{
    use RefreshDatabase;

    private function campaign(): Campaign
    {
        return Campaign::create([
            'user_id' => User::factory()->create()->id,
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'draft',
            'currency' => 'USD',
            'ad_account_id' => 'act_111',
        ]);
    }

    private function onScreen(Campaign $campaign): int
    {
        return (int) $campaign->targetingSet()->value('revision');
    }

    /**
     * The prod sequence, reduced.
     *
     * Both halves carry the revision the screen was rendered with. The first
     * applies and the second is refused, which is the defect as a buyer meets it.
     */
    public function test_the_second_half_of_one_instruction_is_refused(): void
    {
        $campaign = $this->campaign();
        $selections = app(TargetingSelections::class);
        $selections->saveCampaignCountries($campaign, ['US']);

        $stamped = $this->onScreen($campaign);

        $selections->chooseWholeCountries($campaign->fresh(), $stamped);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('Targeting changed since it was opened');

        $selections->saveCampaignCountries($campaign->fresh(), ['US', 'GB'], $stamped);
    }

    /** And the first half did apply, so the campaign is left half-edited. */
    public function test_the_first_half_still_applied(): void
    {
        $campaign = $this->campaign();
        $selections = app(TargetingSelections::class);
        $selections->saveCampaignCountries($campaign, ['US']);

        $stamped = $this->onScreen($campaign);
        $set = $selections->chooseWholeCountries($campaign->fresh(), $stamped);

        try {
            $selections->saveCampaignCountries($campaign->fresh(), ['US', 'GB'], $stamped);
        } catch (RuntimeException) {
            // expected
        }

        $this->assertSame('whole', $set->fresh()->options['geography_scope'] ?? null);
        $this->assertSame(['US'], $selections->countries($campaign->fresh()), 'GB was never added');
    }

    /**
     * The retry is refused too, which is what turned one bad turn into seven.
     *
     * The counter has moved to 2 by now, so a buyer who reads the message and
     * answers "the targeting is at 2 then" is still refused, because the write
     * they are retrying moves it again.
     */
    public function test_retrying_with_the_new_revision_is_also_refused(): void
    {
        $campaign = $this->campaign();
        $selections = app(TargetingSelections::class);
        $selections->saveCampaignCountries($campaign, ['US']);
        $stamped = $this->onScreen($campaign);
        $selections->chooseWholeCountries($campaign->fresh(), $stamped);

        // Second edit refused, then retried against what the counter now reads.
        try {
            $selections->saveCampaignCountries($campaign->fresh(), ['US', 'GB'], $stamped);
        } catch (RuntimeException) {
            // expected
        }

        $selections->saveCampaignCountries($campaign->fresh(), ['US', 'GB'], $this->onScreen($campaign));

        $this->assertSame(['US', 'GB'], $selections->countries($campaign->fresh()),
            'a retry against the current revision does work, so the loop is escapable');
    }

    /** A first edit with no revision is unguarded, as every opening move is. */
    public function test_an_unstamped_edit_is_not_checked(): void
    {
        $campaign = $this->campaign();
        $selections = app(TargetingSelections::class);

        $selections->saveCampaignCountries($campaign, ['US']);
        $selections->saveCampaignCountries($campaign->fresh(), ['US', 'GB']);

        $this->assertSame(['US', 'GB'], $selections->countries($campaign->fresh()));
    }
}
