<?php

namespace Tests\Feature;

use App\Agent\Instructions;
use App\Agent\Workspace;
use App\Campaigns\LaunchFlow;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

/**
 * The launch flow describes reaching the platform, so reaching it ends the flow.
 *
 * LaunchFlow::next() walked the steps whatever the campaign's state, so a
 * published campaign still missing a creative was reported as waiting for one.
 * Instructions turns that into the strongest line in the system prompt - "NEXT
 * STEP ... do not raise anything later in the list unprompted" - and the model
 * obeyed it over whatever had actually been asked.
 *
 * Found on the dev server on 5 Oct. "Add another ad set to this live campaign"
 * was asked four times, twice naming add_ad_set outright. Each time the model
 * acknowledged the request and then called the flow's next step instead. Both
 * add_ad_set and add_ads were unreachable in the product despite being built,
 * registered and covered by tests of their own.
 *
 * outstandingElsewhere() had the rule right from the start - "a campaign already
 * on the platform is not waiting for anything" - and only applied it to
 * siblings. This is the same rule for the campaign in focus.
 */
class PublishingEndsTheLaunchFlowTest extends TestCase
{
    use RefreshDatabase;

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

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

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

    /**
     * Deliberately incomplete: no creative, no ad copy. A real published
     * campaign has those, but a campaign can lose one afterwards and the flow
     * must not restart on it.
     */
    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',
            'landing_url' => 'https://example.com/offer',
            ...$attributes,
        ]);

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

        return $campaign->fresh();
    }

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

    public function test_a_draft_still_has_a_next_step(): void
    {
        $this->assertNotNull(
            app(LaunchFlow::class)->next($this->campaign()),
            'the flow should still drive a campaign that has not been published',
        );
    }

    /** The defect: a live campaign was still being asked for launch steps. */
    public function test_a_published_campaign_has_no_next_step(): void
    {
        $campaign = $this->published();

        $this->assertNotEmpty(
            collect(app(LaunchFlow::class)->progress($campaign))->where('done', false),
            'precondition: this campaign has unfinished steps, which is what used to be reported',
        );

        $this->assertNull(
            app(LaunchFlow::class)->next($campaign),
            'the launch flow kept driving a campaign that is already on the platform',
        );
    }

    /**
     * And the prompt stops steering, which is the thing that mattered.
     *
     * The step name must not appear as the next thing to do, and the actions
     * that do apply to a live campaign must.
     */
    public function test_the_prompt_stops_naming_a_launch_step_once_published(): void
    {
        $campaign = $this->published();
        app(Workspace::class)->focusOn($campaign);

        $prompt = app(Instructions::class)->build();
        $block = substr($prompt, (int) strrpos($prompt, 'NEXT STEP'));

        $this->assertStringContainsString('already on the platform', $block);
        $this->assertStringNotContainsString('Call campaign__import_creatives', $block);
    }

    /** The tools for a live campaign are named somewhere the model will read. */
    public function test_the_prompt_names_what_can_be_done_to_a_live_campaign(): void
    {
        app(Workspace::class)->focusOn($this->published());

        $prompt = app(Instructions::class)->build();

        foreach (['add_ad_set', 'add_ads', 'push_changes'] as $tool) {
            $this->assertStringContainsString(
                $tool,
                $prompt,
                "{$tool} is never mentioned, so the model has no reason to reach for it",
            );
        }
    }

    /** A draft is still steered, so the ordinary build is untouched. */
    public function test_a_draft_is_still_steered_through_the_flow(): void
    {
        app(Workspace::class)->focusOn($this->campaign());

        $prompt = app(Instructions::class)->build();
        $block = substr($prompt, (int) strrpos($prompt, 'NEXT STEP'));

        $this->assertStringNotContainsString('already on the platform', $block);
    }

    /**
     * Siblings were always treated this way; this is the same rule in one more
     * place rather than a new one.
     */
    public function test_a_published_sibling_is_still_not_reported_as_outstanding(): void
    {
        $published = $this->published();

        $this->assertArrayNotHasKey(
            $published->name,
            app(LaunchFlow::class)->outstandingElsewhere($this->campaign(['name' => 'Another'])),
        );
    }
}
