<?php

namespace Tests\Feature;

use App\Campaigns\Publishing\MetaPublisher;
use App\Models\Asset;
use App\Models\AssetPlatformRef;
use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\User;
use App\Services\Meta\Meta;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request as ClientRequest;
use Illuminate\Support\Facades\Http;
use RuntimeException;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

/**
 * The ad set is checked with Meta before any ad set, creative or ad is created.
 *
 * The campaign has had a validate_only dry run since it was written and the ad
 * set never did, which is the wrong way round. A campaign carries five fields
 * Meta rarely argues with. The ad set carries the targeting, the placements, the
 * budget, the bid strategy, the optimisation goal and the promoted object, and
 * every live publish failure so far has been there.
 *
 * What that cost, three times in three days: ads_create_campaign succeeds,
 * ads_create_ad_set is refused, and the buyer is looking at a campaign on their
 * ad account with nothing under it. Through the MCP the refusal arrives as
 * {"error_category":"INTERNAL","error_message":"An internal error occurred.
 * Please try again later.","is_retryable":true} - no field, no value, nothing to
 * act on, and an explicit invitation to retry something that can never succeed.
 * Graph says what is actually wrong. 5 Oct and twice on 7 Oct, ids 172, 549 and
 * 713, two users and two ad accounts.
 *
 * Checking every ad set before creating any of them, rather than each before its
 * own create, so a campaign whose second ad set is unpublishable cannot end up
 * half published.
 *
 * This is the half of the fix that does not need to know what Meta objects to.
 * Objectives::NEVER_ACCEPTED catches PAGE_VIEW in the chat, before a campaign is
 * created at all, and it only covers values production has already refused once.
 * This covers the next one.
 */
class MetaChecksTheAdSetBeforeCreatingAnythingTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

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

        $this->seedVerifiedCountries();

        config([
            'platforms.meta.token' => 'test-token',
            'platforms.meta.mcp.enabled' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['act_111'],
            // Pinned, like every other test that drives the publisher. This was
            // missing and the whole class passed locally and failed on the dev
            // server, which has PLATFORM_PAUSE_ALL_WRITES=true: the kill switch
            // refuses before any request is built, so six tests failed with
            // "All changes to advertising platforms are currently paused" and
            // said nothing about the code under test. A test that reads its
            // preconditions from whatever .env happens to be on the box is not a
            // test.
            'platforms.guardrails.paused' => false,
        ]);

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

    private function fakeMeta(?callable $adsets = null): void
    {
        Http::fake([
            '*/act_111/campaigns' => Http::response(['id' => 'camp-1']),
            '*/act_111/adsets' => $adsets ?? Http::response(['id' => 'adset-1']),
            '*/act_111/adcreatives' => Http::response(['id' => 'creative-1']),
            '*/act_111/ads' => Http::response(['id' => 'ad-1']),
            '*/act_111*' => Http::response([
                'id' => 'act_111', 'name' => 'Test Account',
                'account_status' => 1, 'currency' => 'USD',
            ]),
            '*' => Http::response(['success' => true]),
        ]);
    }

    private function publish(): array
    {
        $campaign = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Attestpath SOC 2',
            'platform' => 'meta',
            'status' => 'draft',
            'objective' => 'OUTCOME_TRAFFIC',
            'ad_account_id' => 'act_111',
            'page_id' => 'page-1',
            'landing_url' => 'https://example.com',
            'budget' => 10,
            'budget_mode' => 'daily',
            'budget_level' => 'adset',
            'currency' => 'USD',
            'locations' => ['countries' => ['US']],
            'placements' => ['facebook'],
        ]);

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

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

        CampaignAd::create([
            'campaign_id' => $campaign->id,
            'headline' => 'Get SOC 2 certified',
            'primary_text' => 'Without doing the work.',
            'cta' => 'LEARN_MORE',
            'asset_id' => $asset->id,
        ]);

        $created = [];

        app(MetaPublisher::class)->create($campaign, 'tester', $created);

        return $created;
    }

    /** Every POST to one endpoint, oldest first. */
    private function postsTo(string $path): array
    {
        $bodies = [];

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

            // str_ends_with, not str_contains: "/adsets" and "/adcreatives" both
            // contain "/ads", which is how a sibling test came to assert on the
            // wrong request and pass.
            if (str_ends_with(rtrim((string) parse_url($request->url(), PHP_URL_PATH), '/'), $path)) {
                $bodies[] = $request->data();
            }
        }

        return $bodies;
    }

    /**
     * The MCP case is covered elsewhere, deliberately not here.
     *
     * This class briefly asserted it with a Meta double and shouldNotReceive
     * ('validateAdSet'), which only ever tested a guard in MetaPublisher. PR #85
     * moved the guard into Meta::validateAdSet() itself, which is the better
     * home - every caller is covered, not just the publisher - and added
     * McpPublishesPausedTest::test_an_mcp_campaign_is_not_used_for_graph_ad_set_validation,
     * which drives a real MCP publish, answers the Graph /adsets endpoint with the
     * exact [100/1815148] "is not a valid campaign id" from production, and
     * asserts Http::assertNotSent for /adsets. That is a stronger assertion than a
     * mock expectation, so duplicating it here would only create a second thing to
     * keep in step.
     */
    /** And it still runs when Graph is the one creating, which is the whole point. */
    public function test_it_still_runs_when_graph_creates_the_campaign(): void
    {
        $this->fakeMeta();

        $this->publish();

        $dryRuns = collect($this->postsTo('/adsets'))
            ->filter(fn (array $body): bool => isset($body['execution_options']));

        $this->assertCount(1, $dryRuns, 'the Graph publish lost its dry run');
    }

    // ------------------------------------------------------- the happy path

    /** The dry run happens, and it is a dry run. */
    public function test_the_ad_set_is_validated_before_it_is_created(): void
    {
        $this->fakeMeta();

        $this->publish();

        $adsets = $this->postsTo('/adsets');

        $this->assertCount(2, $adsets, 'expected one validate_only then one real create');
        $this->assertSame(json_encode(['validate_only']), $adsets[0]['execution_options'] ?? null);
        $this->assertArrayNotHasKey('execution_options', $adsets[1], 'the real create must not be a dry run');
    }

    /**
     * And it carries the same payload as the create, or it proves nothing.
     *
     * A dry run of a different spec is worse than none: it passes, the create
     * fails, and the check is now evidence that the payload was fine.
     */
    public function test_the_dry_run_sends_what_the_create_will_send(): void
    {
        $this->fakeMeta();

        $this->publish();

        [$dry, $real] = $this->postsTo('/adsets');
        unset($dry['execution_options']);

        $this->assertSame($real, $dry);
    }

    /**
     * At both pause levels, because the status is now the thing that differs.
     *
     * The ad set's status used to be PAUSED however the campaign was
     * published, so one assertion covered every case. Since launches began
     * leaving ad sets active beneath a paused campaign it varies with
     * publish_pause_level, and the dry run took its own default - so it
     * validated status PAUSED while the create sent ACTIVE. Checking only the
     * default level would leave that free to come back on the other one.
     */
    public function test_the_dry_run_matches_the_create_at_either_pause_level(): void
    {
        foreach (['campaign' => 'ACTIVE', 'all' => 'PAUSED'] as $level => $expected) {
            config(['platforms.guardrails.publish_pause_level' => $level]);

            $this->fakeMeta();
            $this->publish();

            [$dry, $real] = $this->postsTo('/adsets');
            unset($dry['execution_options']);

            $this->assertSame($expected, $real['status'] ?? null, "the create's status at level {$level}");
            $this->assertSame($real, $dry, "the dry run diverged from the create at level {$level}");
        }
    }

    /** It runs after the campaign, because Meta needs a campaign_id to check against. */
    public function test_it_runs_after_the_campaign_exists(): void
    {
        $this->fakeMeta();

        $this->publish();

        $this->assertSame('camp-1', $this->postsTo('/adsets')[0]['campaign_id'] ?? null);
    }

    // --------------------------------------------------------- the refusal

    /**
     * A refused ad set stops before the ad set, the creative and the ad.
     *
     * The failure Meta returns here is the real one from production, as Graph
     * words it. Through the MCP this same rejection is an INTERNAL with
     * is_retryable true.
     */
    public function test_nothing_is_created_when_the_dry_run_is_refused(): void
    {
        $refusals = 0;

        $this->fakeMeta(function () use (&$refusals) {
            $refusals++;

            return Http::response([
                'error' => [
                    'message' => 'custom_event_type "PAGE_VIEW" is not valid. Did you mean "PDP_VIEW"?',
                    'code' => 100,
                ],
            ], 400);
        });

        try {
            $this->publish();
            $this->fail('the publish should have been refused');
        } catch (RuntimeException $e) {
            $this->assertStringContainsString('PAGE_VIEW', $e->getMessage(), 'Meta\'s own wording should survive');
        }

        $this->assertSame(1, $refusals, 'it should give up on the dry run, not try the create as well');
        $this->assertSame([], $this->postsTo('/adcreatives'), 'a creative was created anyway');
        $this->assertSame([], $this->postsTo('/ads'), 'an ad was created anyway');
    }

    /**
     * Only the campaign is left to roll back.
     *
     * Which is the point of doing this before the ad set rather than after it:
     * the rollback has one object to remove, and MetaPublisher::rollBack already
     * removes it.
     */
    public function test_only_the_campaign_needs_rolling_back(): void
    {
        $this->fakeMeta(fn () => Http::response(['error' => ['message' => 'nope', 'code' => 100]], 400));

        $created = [];

        try {
            app(MetaPublisher::class)->create($this->campaignForRollback(), 'tester', $created);
        } catch (RuntimeException) {
            // expected
        }

        $this->assertSame('camp-1', $created['campaign_id'] ?? null);
        $this->assertSame([], $created['ad_sets'] ?? [], 'an ad set was recorded as created');
        $this->assertSame([], $created['ads'] ?? [], 'an ad was recorded as created');
    }

    private function campaignForRollback(): Campaign
    {
        return Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Attestpath SOC 2',
            'platform' => 'meta',
            'status' => 'draft',
            'objective' => 'OUTCOME_TRAFFIC',
            'ad_account_id' => 'act_111',
            'page_id' => 'page-1',
            'landing_url' => 'https://example.com',
            'budget' => 10,
            'budget_mode' => 'daily',
            'budget_level' => 'adset',
            'currency' => 'USD',
            'locations' => ['countries' => ['US']],
            'placements' => ['facebook'],
        ]);
    }
}
