<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Publisher;
use App\Models\Asset;
use App\Models\AssetPlatformRef;
use App\Models\Campaign;
use App\Models\Decision;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Sleep;
use Illuminate\Support\Str;
use Laravel\Ai\Tools\Request;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

/**
 * What the cleanup could not take back is said, not assumed.
 *
 * Production, 5 Oct. A publish to AutoAutomotive failed at the ad set, the
 * rollback tried to delete the campaign it had just made, and Graph answered
 * "(#10) Application does not have permission for this action" - an MCP-created
 * draft is not reachable over the Graph API, which is the same #10 that made
 * these campaigns unreadable on 30 Sep. The chat reported:
 *
 *   "Nothing was published, and anything created during the attempt was removed."
 *
 * The first half was true. The second was not: campaign 120249729445410510 was
 * still on the account, and nobody was told. That sentence was a constant in the
 * tool, printed whatever the rollback did, because rollBack() returned void and
 * quietlyDelete() swallowed the refusal into a log line.
 *
 * A buyer who is told their account is clean does not go and look.
 */
class AFailedRollbackIsNotReportedAsCleanTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

    private Campaign $campaign;

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

        Sleep::fake();
        $this->seedVerifiedCountries();

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

        $workspace = app(Workspace::class);
        $workspace->bindTo('conv-failed-rollback');
        $workspace->ownedBy(auth()->user());

        config([
            'platforms.guardrails.allowed_ad_accounts' => ['act_111'],
            'platforms.guardrails.max_daily_budget' => 500,
            'platforms.meta.mcp.enabled' => true,
            'platforms.meta.mcp.token' => 'test-token',
            'platforms.meta.token' => 'test-token',
        ]);

        $this->campaign = $this->publishable();
    }

    private function publishable(): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'draft',
            'objective' => 'OUTCOME_TRAFFIC',
            'currency' => 'USD',
            'budget' => 20,
            'budget_mode' => 'daily',
            'budget_level' => 'adset',
            'ad_account_id' => 'act_111',
            'page_id' => 'page-1',
            'landing_url' => 'https://example.com/offer',
            'locations' => ['countries' => ['US']],
            'placements' => ['facebook'],
            'special_ad_categories' => ['NONE'],
        ]);

        $asset = Asset::create([
            'owner_type' => (new User)->getMorphClass(),
            'owner_id' => $campaign->user_id,
            'kind' => 'image', 'source' => 'generated', 'disk' => 'public',
            'path' => 'creatives/x.png', 'original_name' => 'x.png',
            'mime' => 'image/png', 'bytes' => 10, 'checksum' => 'sum',
        ]);

        AssetPlatformRef::create([
            'asset_id' => $asset->id, 'platform' => 'meta',
            'ad_account_id' => 'act_111', 'external_hash' => 'HASH123',
        ]);

        $campaign->ads()->create([
            'headline' => 'Winter Sale',
            'primary_text' => 'Everything reduced.',
            'cta' => 'SHOP_NOW',
            'asset_id' => $asset->id,
        ]);

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

        return $campaign->fresh();
    }

    /**
     * The campaign is created, the ad set is refused, and the delete that
     * follows is refused too. Exactly the production sequence.
     */
    private function fakeCampaignCreatedThenAdSetRefusedAndDeleteRefused(): void
    {
        Http::fake(function ($request) {
            $url = $request->url();
            $method = $request->method();
            $tool = $request->data()['params']['name'] ?? null;

            if ($method === 'DELETE') {
                return Http::response([
                    'error' => ['message' => '(#10) Application does not have permission for this action', 'code' => 10],
                ], 403);
            }

            if ($tool === 'ads_create_ad_set') {
                return Http::response([
                    'error' => ['message' => 'custom_event_type is not valid', 'code' => 100],
                ], 400);
            }

            if ($tool === 'ads_create_campaign') {
                return Http::response(['result' => ['content' => [[
                    'type' => 'text', 'text' => json_encode(['campaign_id' => '120249729445410510']),
                ]]]]);
            }

            if (str_contains($url, 'campaigns')) {
                return Http::response(['id' => '120249729445410510']);
            }

            return Http::response(['id' => 'something']);
        });
    }

    /** @return array<string,mixed> */
    private function publish(): array
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t) => $t->name() === 'campaign__publish_campaign');

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

        $request = new Request([], (string) Str::uuid());
        $this->assertNotNull($tool->shouldRequestApproval($request));

        return json_decode((string) $tool->handle($request), true);
    }

    public function test_a_verified_advertiser_refusal_makes_the_choice_required(): void
    {
        config(['platforms.meta.mcp.enabled' => false]);

        Http::fake(function ($request) {
            if ($request->method() === 'POST' && str_contains($request->url(), '/adsets')) {
                return Http::response([
                    'error' => [
                        'message' => 'Provide a verified advertiser so that ads in this ad set can be delivered',
                        'type' => 'OAuthException',
                        'code' => 100,
                        'error_subcode' => 3858634,
                    ],
                ], 400);
            }

            if ($request->method() === 'POST' && str_contains($request->url(), '/campaigns')) {
                return Http::response(['id' => '1201']);
            }

            if ($request->method() === 'DELETE') {
                return Http::response(['success' => true]);
            }

            return Http::response(['id' => 'page-1']);
        });

        $result = $this->publish();
        $campaign = $this->campaign->fresh();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('3858634', (string) $campaign->last_error);
        $this->assertTrue($campaign->meta['verified_advertiser_required'] ?? false);
    }

    public function test_the_id_left_on_the_account_is_reported(): void
    {
        $this->fakeCampaignCreatedThenAdSetRefusedAndDeleteRefused();

        $result = $this->publish();

        $this->assertFalse($result['ok']);
        $this->assertContains(
            '120249729445410510',
            $result['left_on_platform'] ?? [],
            'the campaign that could not be deleted was not reported: '.json_encode($result),
        );
        Sleep::assertSleptTimes(4);
    }

    /** And the model is told not to describe it as cleaned up. */
    public function test_the_note_does_not_claim_everything_was_removed(): void
    {
        $this->fakeCampaignCreatedThenAdSetRefusedAndDeleteRefused();

        $result = $this->publish();

        $this->assertStringNotContainsString('was removed', $result['note']);
        $this->assertStringContainsString('could not remove everything', $result['note']);
        $this->assertStringContainsString('do not say it was all undone', $result['note']);
    }

    /** It is on the decision too, which is the audit record. */
    public function test_the_decision_records_what_was_left(): void
    {
        $this->fakeCampaignCreatedThenAdSetRefusedAndDeleteRefused();

        $this->publish();

        $decision = Decision::where('action', 'publish_campaign')->latest('id')->firstOrFail();

        $this->assertSame('blocked', $decision->state);
        $this->assertContains('120249729445410510', $decision->result['left_behind'] ?? []);
    }

    /**
     * A rollback that does work still reports a clean account.
     *
     * The point is to say what happened, not to start claiming the opposite.
     */
    public function test_a_clean_rollback_is_reported_as_clean(): void
    {
        Http::fake(function ($request) {
            if ($request->method() === 'DELETE') {
                return Http::response(['success' => true]);
            }

            $tool = $request->data()['params']['name'] ?? null;

            if ($tool === 'ads_create_ad_set') {
                return Http::response(['error' => ['message' => 'nope', 'code' => 100]], 400);
            }

            if ($tool === 'ads_create_campaign') {
                return Http::response(['result' => ['content' => [[
                    'type' => 'text', 'text' => json_encode(['campaign_id' => '120249729445410510']),
                ]]]]);
            }

            return Http::response(['id' => '120249729445410510']);
        });

        $result = $this->publish();

        $this->assertFalse($result['ok']);
        $this->assertArrayNotHasKey('left_on_platform', $result);
        $this->assertStringContainsString('Nothing was left on the platform', $result['note']);
    }

    /** The rollback reports leftovers to its caller rather than only to the log. */
    public function test_the_publisher_returns_what_it_could_not_remove(): void
    {
        $this->fakeCampaignCreatedThenAdSetRefusedAndDeleteRefused();

        $publisher = app(Publisher::class);

        try {
            $publisher->approve($publisher->propose($this->campaign, 'tester'), 'tester');
            $this->fail('publishing should have failed');
        } catch (\Throwable) {
            // The failure is the point; what matters is what it recorded.
        }

        $decision = Decision::where('action', 'publish_campaign')->latest('id')->firstOrFail();

        $this->assertNotEmpty($decision->result['left_behind'] ?? []);
    }
}
