<?php

namespace Tests\Feature;

use App\Agent\NamespacedTool;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\LinkedInManagement;
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 Tests\TestCase;

/**
 * Deleting asks first, and refuses anything that has ever delivered.
 *
 * This is the one irreversible thing the product can do. Meta's own words:
 * "This campaign has been deleted, so it can't be restored and only its name
 * can be changed." There is no undo to offer afterwards.
 *
 * The delivery guard is here because of 9 Oct. A campaign holding 346.61 USD of
 * spend and 66,652 impressions, still delivering, was deleted during a cleanup
 * of test campaigns, on the reasoning that a row in our own table with an
 * external id proved we had created it. Every other campaign in that sweep had
 * zero spend and zero impressions, so one read per object would have separated
 * the one that mattered from the twenty-six that did not. Nothing asked.
 *
 * The local record is cleared only once Meta confirms, which is the other half
 * of that incident: the same cleanup cleared five Google campaigns' ids on the
 * strength of a rollback that reported success having done nothing, leaving
 * live campaigns with no record here at all.
 */
class DeletingNeedsApprovalAndRefusesWhatHasSpentTest 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-delete');
        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;
    }

    /** @param array{spend?: string, impressions?: string} $delivery */
    private function fakeMeta(array $delivery = ['spend' => '0', 'impressions' => '0']): void
    {
        Http::fake([
            '*/insights*' => Http::response(['data' => [$delivery]]),
            '*/adsets*' => Http::response(['data' => [['id' => 'adset-1'], ['id' => 'adset-2']]]),
            '*/ads*' => Http::response(['data' => [['id' => 'ad-1', 'adset_id' => 'adset-1']]]),
            '*' => Http::response(['success' => true]),
        ]);
    }

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

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

        return $tool;
    }

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

    /** @return list<string> object ids a DELETE was sent for */
    private function deletesSent(): array
    {
        $sent = [];

        foreach (Http::recorded() as [$request]) {
            if ($request->method() === 'DELETE') {
                $sent[] = basename((string) parse_url($request->url(), PHP_URL_PATH));
            }
        }

        return $sent;
    }

    // ------------------------------------------------------------- the gating

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

    /** Unconditionally, unlike pausing: there is no undo to fall back on. */
    public function test_it_always_asks_whatever_the_arguments(): void
    {
        $this->campaign();

        foreach ([['entity_type' => 'ad'], ['entity_type' => 'campaign'], []] as $arguments) {
            $this->assertNotNull(
                $this->tool()->shouldRequestApproval(new Request($arguments)),
                'delete skipped approval for '.json_encode($arguments),
            );
        }
    }

    // ------------------------------------------------------- the delivery guard

    /** The 9 Oct defect: a campaign that had spent was deleted anyway. */
    public function test_something_that_has_spent_is_refused_and_nothing_is_deleted(): void
    {
        $this->campaign();
        $this->fakeMeta(['spend' => '346.61', 'impressions' => '66652']);

        $result = $this->removeEntity(['entity_type' => 'campaign']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('has delivered', $result['error']);
        $this->assertSame([], $this->deletesSent(), 'something was deleted despite the refusal');
    }

    public function test_linkedin_delivery_requires_second_confirmation_before_any_deletion(): void
    {
        $campaign = $this->campaign(['platform' => 'linkedin', 'ad_account_id' => '556447014', 'external_campaign_id' => '77']);
        Http::preventStrayRequests();
        $management = $this->mock(LinkedInManagement::class);
        $management->shouldReceive('entity')->with(\Mockery::on(fn (Campaign $given): bool => $given->is($campaign)), 'campaign', '77', \Mockery::any())->andReturn(['id' => 77, 'status' => 'PAUSED']);
        $management->shouldReceive('delivery')->with(\Mockery::on(fn (Campaign $given): bool => $given->is($campaign)), 'campaign', '77', \Mockery::any())
            ->andReturn(['spend' => 346.61, 'impressions' => 66652, 'currency' => 'USD']);
        $management->shouldNotReceive('delete');

        $result = $this->removeEntity(['entity_type' => 'campaign']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('has delivered', $result['error']);
        $this->assertSame(346.61, $result['delivered']['77']['spend']);
        $this->assertSame(66652, $result['delivered']['77']['impressions']);
        $this->assertSame('USD', $result['delivered']['77']['currency']);
        Http::assertNothingSent();
    }

    /** And the numbers come back, so the user hears what they would be destroying. */
    public function test_linkedin_delivered_entity_deletes_only_after_second_confirmation(): void
    {
        $campaign = $this->campaign(['platform' => 'linkedin', 'ad_account_id' => '556447014', 'external_campaign_id' => '77']);
        $management = $this->mock(LinkedInManagement::class);
        $management->shouldReceive('delivery')->twice()->andReturn(['spend' => 346.61, 'impressions' => 66652, 'currency' => 'USD']);
        $management->shouldReceive('delete')->once()->with(\Mockery::on(fn (Campaign $given): bool => $given->is($campaign)), 'campaign', '77', \Mockery::any(), true)
            ->andReturn(['id' => '77', 'deleted' => false, 'pending_deletion' => true]);
        Http::preventStrayRequests();

        $firstRequest = new Request(['entity_type' => 'campaign'], 'linkedin-delete-first');
        $this->tool()->shouldRequestApproval($firstRequest);
        $first = json_decode((string) $this->tool()->handle($firstRequest), true);

        $secondRequest = new Request(['entity_type' => 'campaign', 'delete_even_though_it_delivered' => true], 'linkedin-delete-confirmed');
        $this->tool()->shouldRequestApproval($secondRequest);
        $second = json_decode((string) $this->tool()->handle($secondRequest), true);

        $this->assertFalse($first['ok']);
        $this->assertTrue($second['ok']);
        $this->assertTrue($second['results'][0]['pending_deletion']);
        $this->assertDatabaseHas('campaigns', ['id' => $campaign->id, 'external_campaign_id' => '77']);
        Http::assertNothingSent();
    }

    public function test_linkedin_batch_delivery_is_checked_before_deleting_any_entity(): void
    {
        $this->campaign(['platform' => 'linkedin', 'ad_account_id' => '556447014', 'external_campaign_id' => '77']);
        $management = $this->mock(LinkedInManagement::class);
        $management->shouldReceive('entity')->andReturn(['id' => '99']);
        $management->shouldReceive('delivery')->with(\Mockery::any(), 'creative', '99', \Mockery::any())
            ->andReturn(['spend' => 0.0, 'impressions' => 0, 'currency' => 'USD']);
        $management->shouldReceive('delivery')->with(\Mockery::any(), 'creative', '100', \Mockery::any())
            ->andReturn(['spend' => 0.0, 'impressions' => 412, 'currency' => 'USD']);
        $management->shouldNotReceive('delete');

        $result = $this->removeEntity(['entity_type' => 'creative', 'ids' => ['99', '100']]);

        $this->assertFalse($result['ok']);
        $this->assertSame(412, $result['delivered']['100']['impressions']);
    }

    public function test_linkedin_deletion_approval_displays_reviewed_delivery_figures(): void
    {
        $this->campaign(['platform' => 'linkedin', 'ad_account_id' => '556447014', 'external_campaign_id' => '77']);
        $management = $this->mock(LinkedInManagement::class);
        $management->shouldReceive('delivery')->andReturn(['spend' => 346.61, 'impressions' => 66652, 'currency' => 'USD']);

        $approval = $this->tool()->shouldRequestApproval(new Request(['entity_type' => 'campaign'], 'linkedin-delete-review'));

        $this->assertStringContainsString('346.61 USD spent', $approval->reason);
        $this->assertStringContainsString('66652 impressions', $approval->reason);
        $this->assertStringContainsString('second confirmation', $approval->reason);
    }

    public function test_linkedin_reporting_failure_refuses_even_an_explicit_confirmation(): void
    {
        $campaign = $this->campaign(['platform' => 'linkedin', 'ad_account_id' => '556447014', 'external_campaign_id' => '77']);
        Http::preventStrayRequests();
        $management = $this->mock(LinkedInManagement::class);
        $management->shouldReceive('entity')->andReturn(['id' => 77, 'status' => 'PAUSED']);
        $management->shouldReceive('delivery')->andThrow(new \RuntimeException('Reporting permission is unavailable; unknown spend is not zero.'));
        $management->shouldNotReceive('delete');

        $result = $this->removeEntity(['entity_type' => 'campaign', 'delete_even_though_it_delivered' => true]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('unknown spend', $result['error']);
        $this->assertDatabaseHas('campaigns', ['id' => $campaign->id, 'external_campaign_id' => '77']);
        Http::assertNothingSent();
    }

    public function test_the_refusal_carries_the_spend_and_impressions(): void
    {
        $this->campaign();
        $this->fakeMeta(['spend' => '346.61', 'impressions' => '66652']);

        $result = $this->removeEntity(['entity_type' => 'campaign']);

        $this->assertSame(346.61, $result['delivered']['120252047635070626']['spend']);
        $this->assertSame(66652, $result['delivered']['120252047635070626']['impressions']);
        $this->assertStringContainsString('cannot be undone', $result['note']);
        $this->assertStringContainsString('pausing it instead', $result['note']);
    }

    /** Impressions alone are enough - a campaign can deliver before it is billed. */
    public function test_impressions_without_spend_still_refuse(): void
    {
        $this->campaign();
        $this->fakeMeta(['spend' => '0', 'impressions' => '412']);

        $this->assertFalse($this->removeEntity(['entity_type' => 'campaign'])['ok']);
        $this->assertSame([], $this->deletesSent());
    }

    /** Confirmed a second time, it goes. */
    public function test_an_explicit_confirmation_lets_it_through(): void
    {
        $this->campaign();
        $this->fakeMeta(['spend' => '346.61', 'impressions' => '66652']);

        $result = $this->removeEntity([
            'entity_type' => 'campaign',
            'delete_even_though_it_delivered' => true,
        ]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertContains('120252047635070626', $this->deletesSent());
    }

    /** Something that never ran needs no second confirmation. */
    public function test_a_campaign_that_never_delivered_deletes_first_time(): void
    {
        $this->campaign();
        $this->fakeMeta();

        $result = $this->removeEntity(['entity_type' => 'campaign']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertContains('120252047635070626', $this->deletesSent());
    }

    // -------------------------------------------------------------- the order

    /** Deepest first: Meta refuses a parent that still has children. */
    public function test_a_campaign_deletes_its_ads_and_ad_sets_before_itself(): void
    {
        $this->campaign();
        $this->fakeMeta();

        $this->removeEntity(['entity_type' => 'campaign']);

        $sent = $this->deletesSent();
        $campaignAt = array_search('120252047635070626', $sent, true);

        $this->assertNotFalse($campaignAt, 'the campaign was never deleted');
        $this->assertLessThan($campaignAt, array_search('ad-1', $sent, true), 'the ad went after the campaign');
        $this->assertLessThan($campaignAt, array_search('adset-1', $sent, true), 'the ad set went after the campaign');
    }

    // ------------------------------------------------------- the local record

    /** Cleared only when Meta confirmed, so the record matches the account. */
    public function test_the_local_id_is_cleared_on_a_confirmed_delete(): void
    {
        $campaign = $this->campaign();
        $this->fakeMeta();

        $this->removeEntity(['entity_type' => 'campaign']);

        $this->assertNull($campaign->fresh()->external_campaign_id);
        $this->assertSame('draft', $campaign->fresh()->status);
    }

    /** The other half of 9 Oct: a failed delete must not clear the id. */
    public function test_a_failed_delete_leaves_the_local_id_alone(): void
    {
        $campaign = $this->campaign();

        Http::fake([
            '*/insights*' => Http::response(['data' => [['spend' => '0', 'impressions' => '0']]]),
            '*/adsets*' => Http::response(['data' => []]),
            '*/ads*' => Http::response(['data' => []]),
            '*' => Http::response(['error' => ['message' => '(#10) Application does not have permission']], 403),
        ]);

        $result = $this->removeEntity(['entity_type' => 'campaign']);

        $this->assertFalse($result['ok']);
        $this->assertSame('120252047635070626', $campaign->fresh()->external_campaign_id);
        $this->assertStringContainsString('still on the account', $result['note']);
    }

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

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

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

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

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

        $result = $this->removeEntity(['entity_type' => 'campaign']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('nothing on Meta to delete', $result['error']);
        Http::assertNothingSent();
    }

    /**
     * A platform that cannot delete is named rather than half-tried.
     *
     * This asked about Google, which can now delete - see
     * AGoogleEntityCanBeDeletedOrEditedTest, where the same delivery guard runs
     * against Google's own all-time spend and impressions. LinkedIn carried the
     * case next and has since grown its own branch here, so the stand-in has
     * moved again: what is tested is that an unsupported platform is refused
     * before any call is made, not that one in particular is unsupported.
     */
    public function test_a_platform_that_cannot_delete_is_refused_by_name(): void
    {
        $this->campaign(['platform' => 'tiktok', 'ad_account_id' => '3460855874']);
        Http::fake();

        $result = $this->removeEntity(['entity_type' => 'campaign']);

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

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

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

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

    /** An unreadable platform stops it: nothing is deleted on a guess. */
    public function test_an_unreadable_platform_deletes_nothing(): void
    {
        $this->campaign();

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

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

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