<?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;

/**
 * "Is it already running" is asked of the platform, not of our own column.
 *
 * activated_at is written in exactly one place - Publisher::activate() - so a
 * campaign brought under management by CampaignImporter has it null however live
 * it is. Every check that read local state alone was therefore wrong for every
 * adopted campaign, and the one standing in front of activation is the one that
 * matters: it would offer to start a campaign already spending.
 *
 * Asked on demand rather than cached at adoption, because a stored status is
 * only true until somebody opens Ads Manager, and this is a question whose wrong
 * answer costs money. Only on paths a person initiated - it is a platform read
 * and it counts against the hourly budget.
 *
 * Null is kept distinct from false throughout. LinkedIn has no campaign status
 * reader at all, and answering false there would be indistinguishable from a
 * real "it is not running".
 */
class RunningStateIsAskedOfThePlatformTest 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:*'],
            'platforms.guardrails.paused' => false,
        ]);

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

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

    /** What adoption leaves: an external id, and activated_at null. */
    private function adopted(string $platform = 'meta'): Campaign
    {
        return Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Adopted campaign',
            'platform' => $platform,
            'status' => 'published',
            'objective' => 'OUTCOME_TRAFFIC',
            'ad_account_id' => $platform === 'meta' ? 'act_111' : '3460855874',
            'currency' => 'USD',
            'budget' => 25,
            'budget_mode' => 'daily',
            'external_campaign_id' => '120252047635070626',
            'external_ids' => ['campaign_id' => '120252047635070626'],
        ]);
    }

    private function metaSays(string $effectiveStatus): void
    {
        Http::fake(['*' => Http::response([
            'id' => '120252047635070626',
            'name' => 'Adopted campaign',
            'status' => $effectiveStatus,
            'effective_status' => $effectiveStatus,
        ])]);
    }

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

    public function test_an_active_campaign_reads_as_live(): void
    {
        $this->metaSays('ACTIVE');

        $this->assertTrue(app(Publisher::class)->isLiveOnPlatform($this->adopted(), 'tester'));
    }

    public function test_a_paused_campaign_reads_as_not_live(): void
    {
        $this->metaSays('PAUSED');

        $this->assertFalse(app(Publisher::class)->isLiveOnPlatform($this->adopted(), 'tester'));
    }

    /**
     * effective_status wins over status.
     *
     * A campaign the advertiser set ACTIVE under a disabled account is not
     * running, and status alone cannot tell you that.
     */
    public function test_effective_status_decides(): void
    {
        Http::fake(['*' => Http::response([
            'id' => '120252047635070626',
            'status' => 'ACTIVE',
            'effective_status' => 'ACCOUNT_DISABLED',
        ])]);

        $this->assertFalse(app(Publisher::class)->isLiveOnPlatform($this->adopted(), 'tester'));
    }

    /** A failed read is null, never false. */
    public function test_a_failed_read_is_not_knowable(): void
    {
        Http::fake(['*' => Http::response(['error' => ['message' => 'Unsupported get request']], 400)]);

        $this->assertNull(app(Publisher::class)->isLiveOnPlatform($this->adopted(), 'tester'));
    }

    /** An unpublished campaign is not asked about at all. */
    public function test_an_unpublished_campaign_is_never_asked(): void
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Draft',
            'platform' => 'meta',
            'status' => 'draft',
            'ad_account_id' => 'act_111',
            'currency' => 'USD',
        ]);

        Http::fake();

        $this->assertNull(app(Publisher::class)->isLiveOnPlatform($campaign, 'tester'));
        Http::assertNothingSent();
    }

    /** LinkedIn has no reader, so it says so rather than guessing. */
    public function test_linkedin_cannot_tell(): void
    {
        Http::fake();

        $this->assertNull(app(Publisher::class)->isLiveOnPlatform($this->adopted('linkedin'), 'tester'));
    }

    // ------------------------------------------------- what the checks now do

    /** The defect: activation was offered for a live adopted campaign. */
    public function test_activation_is_refused_for_a_live_adopted_campaign(): void
    {
        $this->metaSays('ACTIVE');

        $problems = app(Publisher::class)->activationProblems($this->adopted(), 'tester');

        $this->assertContains('it is already running', $problems);
    }

    /** And still offered when the platform says it is paused. */
    public function test_activation_is_not_refused_when_the_platform_says_paused(): void
    {
        $this->metaSays('PAUSED');

        $problems = app(Publisher::class)->activationProblems($this->adopted(), 'tester');

        $this->assertNotContains('it is already running', $problems);
    }

    /**
     * When the platform cannot be asked, local state decides - which is the
     * behaviour this had before, so an unreadable platform is no worse than it
     * used to be rather than newly permissive.
     */
    public function test_an_unreadable_platform_falls_back_to_local_state(): void
    {
        Http::fake(['*' => Http::response(['error' => ['message' => 'nope']], 400)]);

        $campaign = $this->adopted();
        $campaign->update(['activated_at' => now()]);

        $this->assertContains('it is already running', app(Publisher::class)->activationProblems($campaign->fresh(), 'tester'));
    }

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

    /** The tool refuses, and does not invent a date it does not have. */
    public function test_the_request_tool_refuses_without_inventing_a_start_date(): void
    {
        $campaign = $this->adopted();
        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign);

        $this->metaSays('ACTIVE');

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

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('already running', $result['error']);
        $this->assertStringNotContainsString('running since', $result['error']);
    }

    /** And it still gives the date for a campaign this product started itself. */
    public function test_a_campaign_we_started_still_reports_when(): void
    {
        $campaign = $this->adopted();
        $campaign->update(['activated_at' => now()->subDays(3)]);
        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign->fresh());

        $this->metaSays('ACTIVE');

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

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('running since', $result['error']);
    }

    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;
    }
}
