<?php

namespace Tests\Feature;

use App\Agent\NamespacedTool;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Http\Controllers\ChatController;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Contracts\Approvable;
use Laravel\Ai\Tools\Request;
use ReflectionMethod;
use Tests\TestCase;

/**
 * One ad set or one ad can be stopped, without stopping the campaign.
 *
 * The campaign was the only level anything could reach: pause_campaign and
 * activate_campaign, and nothing in between. A buyer who wanted a single losing
 * ad switched off had to do it in Ads Manager - and until the restart
 * asymmetry was fixed, the chat would turn it back on again at the next start.
 *
 * Two rules this encodes, and both are tested in both directions.
 *
 * An id is never acted on unless it was just read under the campaign in focus.
 * The account allow list says which account may be written to, not which object
 * inside it, so an id from an earlier turn - or one the model invented in the
 * right shape - would otherwise reach a stranger's ad set on a permitted
 * account.
 *
 * Restarting is asked about only when it can spend. Pausing never is, and
 * restarting under a campaign that is itself paused never is either, because
 * the campaign gates its whole tree. Restarting under a live campaign begins
 * delivery, which is the one thing approvals exist for here.
 */
class AdSetsAndAdsCanBePausedIndividuallyTest 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-entity-status');
        app(Workspace::class)->ownedBy($this->user);
    }

    private function campaign(array $attributes = []): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'published',
            'objective' => 'OUTCOME_TRAFFIC',
            'ad_account_id' => 'act_111',
            'currency' => 'USD',
            'budget' => 25,
            'budget_mode' => 'daily',
            'external_campaign_id' => '120252047635070626',
            ...$attributes,
        ]);

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

        return $campaign;
    }

    /** The campaign read answers the live-state question; the edges answer ownership. */
    private function fakeMeta(string $campaignStatus = 'PAUSED'): void
    {
        Http::fake([
            '*/adsets*' => Http::response(['data' => [['id' => 'adset-1'], ['id' => 'adset-2']]]),
            '*/ads*' => Http::response(['data' => [['id' => 'ad-1', 'adset_id' => 'adset-1']]]),
            '*120252047635070626*' => Http::response([
                'id' => '120252047635070626',
                'status' => $campaignStatus,
                'effective_status' => $campaignStatus,
            ]),
            '*' => Http::response(['success' => true]),
        ]);
    }

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

        $this->assertNotNull($tool, 'campaign__set_entity_status is not registered');

        return $tool;
    }

    private function setStatus(array $arguments): array
    {
        return json_decode((string) $this->tool()->handle(new Request($arguments)), true);
    }

    /** @return array<int,string> status written per object id */
    private function statusWrites(): array
    {
        $written = [];

        foreach (Http::recorded() as [$request]) {
            if ($request->method() !== 'POST') {
                continue;
            }

            if ($status = $request->data()['status'] ?? null) {
                $written[basename((string) parse_url($request->url(), PHP_URL_PATH))] = $status;
            }
        }

        return $written;
    }

    // ------------------------------------------------------------- pausing

    public function test_one_ad_set_can_be_paused(): void
    {
        $this->campaign();
        $this->fakeMeta();

        $result = $this->setStatus(['entity_type' => 'ad_set', 'ids' => ['adset-2'], 'status' => 'PAUSED']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['adset-2'], $result['changed']);
        $this->assertSame(['adset-2' => 'PAUSED'], $this->statusWrites());
    }

    public function test_one_ad_can_be_paused(): void
    {
        $this->campaign();
        $this->fakeMeta();

        $result = $this->setStatus(['entity_type' => 'ad', 'ids' => ['ad-1'], 'status' => 'PAUSED']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['ad-1' => 'PAUSED'], $this->statusWrites());
    }

    /** Pausing is never gated: approvals stand between a buyer and spending. */
    public function test_pausing_needs_no_approval(): void
    {
        $this->campaign();
        $this->fakeMeta('ACTIVE');

        $this->assertNull($this->tool()->shouldRequestApproval(
            new Request(['entity_type' => 'ad', 'ids' => ['ad-1'], 'status' => 'PAUSED']),
        ));
    }

    // ------------------------------------------------------------ restarting

    /** Under a paused campaign nothing can spend, so no approval is needed. */
    public function test_restarting_under_a_paused_campaign_needs_no_approval(): void
    {
        $this->campaign();
        $this->fakeMeta('PAUSED');

        $this->assertNull($this->tool()->shouldRequestApproval(
            new Request(['entity_type' => 'ad', 'ids' => ['ad-1'], 'status' => 'ACTIVE']),
        ));
    }

    /** Under a live campaign it begins delivery, so it is asked about. */
    public function test_restarting_under_a_live_campaign_requires_approval(): void
    {
        $this->campaign();
        $this->fakeMeta('ACTIVE');

        $this->assertNotNull($this->tool()->shouldRequestApproval(
            new Request(['entity_type' => 'ad', 'ids' => ['ad-1'], 'status' => 'ACTIVE']),
        ));
    }

    /** An unreadable campaign is asked about too: null is not "safe". */
    public function test_restarting_asks_when_the_platform_cannot_be_read(): void
    {
        $this->campaign();

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

        $this->assertNotNull($this->tool()->shouldRequestApproval(
            new Request(['entity_type' => 'ad', 'ids' => ['ad-1'], 'status' => 'ACTIVE']),
        ));
    }

    public function test_the_tool_is_approval_gated_at_all(): void
    {
        $this->assertInstanceOf(Approvable::class, $this->tool()->inner());
    }

    // ------------------------------------------------------- id ownership

    /** The defect this prevents: acting on an id that is not in this campaign. */
    public function test_an_id_outside_the_campaign_is_refused_and_nothing_is_written(): void
    {
        $this->campaign();
        $this->fakeMeta();

        $result = $this->setStatus(['entity_type' => 'ad_set', 'ids' => ['adset-999'], 'status' => 'PAUSED']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('adset-999', $result['error']);
        $this->assertStringContainsString('nothing was changed', $result['error']);
        $this->assertSame([], $this->statusWrites());
    }

    /** All or nothing: one bad id in a list leaves the good ones untouched too. */
    public function test_a_single_unknown_id_stops_the_whole_batch(): void
    {
        $this->campaign();
        $this->fakeMeta();

        $result = $this->setStatus([
            'entity_type' => 'ad_set',
            'ids' => ['adset-1', 'adset-999'],
            'status' => 'PAUSED',
        ]);

        $this->assertFalse($result['ok']);
        $this->assertSame([], $this->statusWrites(), 'a valid id was written despite the batch being refused');
    }

    /** An ad id passed as an ad set is not in the ad set list, so it is refused. */
    public function test_the_level_has_to_match_the_id(): void
    {
        $this->campaign();
        $this->fakeMeta();

        $result = $this->setStatus(['entity_type' => 'ad_set', 'ids' => ['ad-1'], 'status' => 'PAUSED']);

        $this->assertFalse($result['ok']);
        $this->assertSame([], $this->statusWrites());
    }

    // ------------------------------------------------------------ the refusals

    public function test_an_unpublished_campaign_is_refused(): void
    {
        $this->campaign(['external_campaign_id' => null, 'status' => 'draft']);
        Http::fake();

        $result = $this->setStatus(['entity_type' => 'ad', 'ids' => ['ad-1'], 'status' => 'PAUSED']);

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

    /**
     * A platform that cannot pause one entity is named rather than half-tried.
     *
     * This asked about Google, which can now do it - see
     * AGoogleAdGroupOrAdCanBePausedTest. LinkedIn carried the case next, and
     * then grew its own branch here too, so the stand-in has moved again. What
     * is being tested is that an unsupported platform is refused before
     * anything is sent, not that any particular one is unsupported.
     */
    public function test_a_platform_that_cannot_do_this_is_refused_by_name(): void
    {
        $this->campaign(['platform' => 'tiktok', 'ad_account_id' => '3460855874']);
        Http::fake();

        $result = $this->setStatus(['entity_type' => 'ad', 'ids' => ['ad-1'], 'status' => 'PAUSED']);

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

    public function test_no_ids_is_refused_without_a_call(): void
    {
        $this->campaign();
        Http::fake();

        $result = $this->setStatus(['entity_type' => 'ad', 'ids' => [], 'status' => 'PAUSED']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('No ids were given', $result['error']);
        Http::assertNothingSent();
    }

    /** A bounded batch, so a mistake cannot sweep a whole account. */
    public function test_too_many_ids_at_once_is_refused(): void
    {
        $this->campaign();
        Http::fake();

        $result = $this->setStatus([
            'entity_type' => 'ad',
            'ids' => array_map(static fn (int $i): string => 'ad-'.$i, range(1, 21)),
            'status' => 'PAUSED',
        ]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('up to 20 at a time', $result['error']);
        Http::assertNothingSent();
    }

    /** A partial failure is named, not averaged into one cheerful word. */
    public function test_a_partial_failure_names_what_is_still_running(): void
    {
        $this->campaign();

        Http::fake([
            '*/adsets*' => Http::response(['data' => [['id' => 'adset-1'], ['id' => 'adset-2']]]),
            '*adset-2*' => Http::response(['error' => ['message' => 'Invalid parameter']], 400),
            '*' => Http::response(['success' => true]),
        ]);

        $result = $this->setStatus([
            'entity_type' => 'ad_set',
            'ids' => ['adset-1', 'adset-2'],
            'status' => 'PAUSED',
        ]);

        $this->assertSame(['adset-1'], $result['changed']);
        $this->assertArrayHasKey('adset-2', $result['failed']);
        $this->assertStringContainsString('do not describe this as done', $result['note']);
    }

    /** Live objects are changed with POST /{id} status, including while MCP is configured. */
    public function test_unpausing_posts_active_on_the_object_and_skips_mcp(): void
    {
        config([
            'platforms.meta.mcp.enabled' => true,
            'platforms.meta.mcp.token' => 'test-mcp-token',
            'platforms.meta.mcp.endpoint' => 'https://meta-mcp.example.test/mcp',
        ]);
        $this->campaign();
        $this->fakeMeta();

        $result = $this->setStatus(['entity_type' => 'ad_set', 'ids' => ['adset-2'], 'status' => 'ACTIVE']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['adset-2' => 'ACTIVE'], $this->statusWrites());
        Http::assertNotSent(fn ($request): bool => str_contains($request->url(), 'meta-mcp.example.test'));
    }

    public function test_the_campaign_itself_is_paused_with_one_status_post(): void
    {
        $this->campaign();
        $this->fakeMeta('ACTIVE');

        $result = $this->setStatus(['entity_type' => 'campaign', 'status' => 'PAUSED', 'ids' => []]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['120252047635070626' => 'PAUSED'], $this->statusWrites());
    }

    public function test_asking_in_chat_unpauses_the_named_ad_set_and_quotes_effective_status(): void
    {
        $this->campaign();
        Http::fake([
            '*/adsets*' => Http::response(['data' => [['id' => '120252584247030100']]]),
            '*120252584247030100*' => Http::response([
                'id' => '120252584247030100',
                'success' => true,
                'status' => 'ACTIVE',
                'effective_status' => 'CAMPAIGN_PAUSED',
            ]),
            '*' => Http::response(['success' => true]),
        ]);

        $reply = (new ReflectionMethod(ChatController::class, 'entityStatusFromMessage'))
            ->invoke(app(ChatController::class), 'unpause this adset id 120252584247030100');

        $this->assertSame(
            'Ad set 120252584247030100 is active. Meta status is ACTIVE and effective status is CAMPAIGN_PAUSED. It is not delivering because the campaign is paused.',
            $reply,
        );
        $this->assertSame(['120252584247030100' => 'ACTIVE'], $this->statusWrites());
    }

    public function test_an_ad_set_can_be_archived_and_the_user_is_asked_first(): void
    {
        $this->campaign();
        $this->fakeMeta('ACTIVE');

        $approval = $this->tool()->shouldRequestApproval(new Request([
            'entity_type' => 'ad_set',
            'ids' => ['adset-1'],
            'status' => 'ARCHIVED',
        ], 'call-archive-1'));

        $this->assertNotNull($approval);
        $this->assertStringContainsString('cannot be turned back on', (string) $approval->reason);

        $result = $this->setStatus(['entity_type' => 'ad_set', 'ids' => ['adset-1'], 'status' => 'ARCHIVED']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['adset-1' => 'ARCHIVED'], $this->statusWrites());
        $this->assertStringContainsString('cannot be turned back on', $result['note']);
    }
}
