<?php

namespace Tests\Feature;

use App\Agent\NamespacedTool;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Publisher;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * A campaign this product did not start can still be stopped.
 *
 * pause() asked isRunning(), which is isPublished() && activated_at !== null,
 * and activated_at is written by exactly one place - Publisher::activate().
 * CampaignImporter writes external_campaign_id and status=published and never
 * touches activated_at (grep returns zero hits in that file), so every adopted
 * campaign read as "not running".
 *
 * The consequence was not a silent no-op, which would have been bad enough.
 * PauseCampaign checked isRunning() itself, before the publisher was reached,
 * and returned ok=true with "It was already paused and is not spending. Say so
 * in one line." So the chat told a buyer who had adopted a live, spending
 * campaign that it was already stopped, and never called Meta at all. Adopting
 * a running campaign and asking the chat to halt it is the entire point of
 * open_campaign, and it was the one case that could not work.
 */
class AnAdoptedCampaignCanBeStoppedTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

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

        config([
            'platforms.meta.token' => 'test-token',
            'platforms.meta.mcp.enabled' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['meta:*'],
            // Pinned, because the dev server sets it and writes would be refused.
            'platforms.guardrails.paused' => false,
        ]);

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

        app(Workspace::class)->bindTo('conv-adopted-pause');
        app(Workspace::class)->ownedBy($this->user);
    }

    /**
     * Exactly what adoption leaves behind: an external id, status published,
     * and activated_at null because nothing ever set it.
     */
    private function adoptedCampaign(): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Somebody else\'s live campaign',
            'platform' => 'meta',
            'status' => 'published',
            'objective' => 'OUTCOME_TRAFFIC',
            'ad_account_id' => 'act_111',
            'currency' => 'USD',
            'budget' => 25,
            'budget_mode' => 'daily',
            'external_campaign_id' => '120252047635070626',
            'external_ids' => ['campaign_id' => '120252047635070626'],
        ]);

        $this->assertTrue($campaign->isPublished(), 'fixture should read as published');
        $this->assertNull($campaign->activated_at, 'adoption never writes activated_at');
        $this->assertFalse($campaign->isRunning(), 'which is exactly why this broke');

        return $campaign;
    }

    private function tool(string $name): NamespacedTool
    {
        $tool = collect(app(ToolRegistry::class)->resolve())->first(fn ($t) => $t->name() === $name);

        $this->assertNotNull($tool, "{$name} is not registered");

        return $tool;
    }

    // ------------------------------------------------------------ the publisher

    /** The defect: the platform was never asked. */
    public function test_pausing_an_adopted_campaign_reaches_the_platform(): void
    {
        $campaign = $this->adoptedCampaign();

        Http::fake(['*' => Http::response(['success' => true])]);

        app(Publisher::class)->pause($campaign, 'tester');

        Http::assertSent(fn ($request): bool => str_contains($request->url(), '120252047635070626')
            && ($request->data()['status'] ?? null) === 'PAUSED');
    }

    /** And only the campaign, which is enough to halt delivery. */
    public function test_it_pauses_the_campaign_and_nothing_below_it(): void
    {
        $campaign = $this->adoptedCampaign();
        $campaign->primaryAdSet->update(['external_adset_id' => 'adset-1', 'status' => 'published']);

        Http::fake(['*' => Http::response(['success' => true])]);

        app(Publisher::class)->pause($campaign, 'tester');

        $touched = collect(Http::recorded())
            ->filter(fn (array $pair): bool => ($pair[0]->data()['status'] ?? null) !== null)
            ->map(fn (array $pair): string => $pair[0]->url());

        $this->assertTrue($touched->contains(fn (string $url): bool => str_contains($url, '120252047635070626')));
        $this->assertFalse(
            $touched->contains(fn (string $url): bool => str_contains($url, 'adset-1')),
            'pausing reached down into the ad sets',
        );
    }

    // ----------------------------------------------------------------- the tool

    /**
     * The part that made it a money bug rather than a missing feature.
     *
     * The old reply was ok=true with "already paused and is not spending",
     * which the model was instructed to say in one line.
     */
    public function test_the_tool_does_not_claim_an_adopted_campaign_is_already_paused(): void
    {
        $this->adoptedCampaignInFocus();

        Http::preventStrayRequests();
        Http::fake(['*/120252047635070626*' => Http::sequence()
            ->push(['success' => true])
            ->push(['id' => '120252047635070626', 'status' => 'PAUSED', 'effective_status' => 'PAUSED'])]);

        $result = json_decode((string) $this->tool('campaign__pause_campaign')->handle(new Request([])), true);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertFalse($result['running']);
        $this->assertStringNotContainsString('already paused', (string) ($result['note'] ?? ''));
        $this->assertStringContainsString('stopped spending', (string) ($result['note'] ?? ''));
        Http::assertSentCount(2);
        Http::assertSent(fn ($request): bool => $request->method() === 'POST'
            && $request['status'] === 'PAUSED');
        Http::assertSent(fn ($request): bool => $request->method() === 'GET'
            && str_contains($request['fields'], 'status'));
    }

    /** A platform refusal is reported as one, rather than as a stop. */
    public function test_a_refused_pause_is_not_reported_as_stopped(): void
    {
        $this->adoptedCampaignInFocus();

        Http::fake(['*' => Http::response(['error' => ['message' => 'Unsupported post request']], 400)]);

        $result = json_decode((string) $this->tool('campaign__pause_campaign')->handle(new Request([])), true);

        $this->assertFalse($result['ok']);
        $this->assertTrue($result['running']);
        $this->assertStringContainsString('may still be spending', (string) ($result['note'] ?? ''));
    }

    /** An unpublished draft still has nothing to stop, and that is not a failure. */
    public function test_an_unpublished_campaign_is_still_refused_without_a_call(): void
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Draft',
            'platform' => 'meta',
            'status' => 'draft',
            'ad_account_id' => 'act_111',
            'currency' => 'USD',
        ]);

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

        Http::fake();

        $result = json_decode((string) $this->tool('campaign__pause_campaign')->handle(new Request([])), true);

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

    private function adoptedCampaignInFocus(): Campaign
    {
        $campaign = $this->adoptedCampaign();

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

        return $campaign;
    }
}
