<?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 Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request as ClientRequest;
use Illuminate\Support\Facades\Http;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

/**
 * Meta creates the campaign, the ad set and the ad paused.
 *
 * Every "it will be created paused" the chat says rests on this, and nothing
 * checked it. Google has test_every_level_google_creates_is_paused and LinkedIn
 * has LinkedInKillSwitchCoversEveryCreateTest; Meta, the platform this product
 * publishes to most, had no assertion anywhere - `grep -rn PAUSED tests/`
 * returned nothing for it. GooglePublisherTest's own docblock cites "it differed
 * from Meta, where campaign, ad set and ad are all paused" as established fact,
 * and that fact was resting on nothing.
 *
 * Found by mutation on 29 Sep: changing all three 'status' => 'PAUSED' in
 * GraphApi to 'ACTIVE' left the whole suite green at 1699 passing. A Meta
 * campaign published ACTIVE starts spending the moment it is created, and the
 * buyer has been told the opposite.
 *
 * Asserted on the request bodies that actually went out rather than on a spec
 * built here, because the defect being guarded against lives between the spec
 * and the wire.
 */
class EveryLevelMetaCreatesIsPausedTest 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'],
        ]);

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

        Http::fake([
            '*/act_111/campaigns' => Http::response(['id' => 'camp-1']),
            '*/act_111/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',
                'user_tasks' => ['DRAFT', 'ANALYZE', 'ADVERTISE', 'MANAGE'], 'account_status' => 1, 'currency' => 'USD',
            ]),
            '*' => Http::response(['success' => true]),
        ]);
    }

    private function publish(): void
    {
        $campaign = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Winter Sale',
            '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'],
        ]);

        // A real asset with a platform reference, because the creative step
        // reads $ad->asset->refFor(...) and the ad is created after it. Without
        // one the publish stops at the creative and the ads endpoint is never
        // reached, which is how the first version of this test came to assert
        // nothing about the ad at all.
        $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' => 'Winter Sale',
            'primary_text' => 'Everything reduced.',
            'cta' => 'SHOP_NOW',
            'asset_id' => $asset->id,
        ]);

        $created = [];

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

    /**
     * The body Meta was sent for one endpoint: the real create, matched on the
     * whole path.
     *
     * Two ways this was quietly wrong, both of which let the file pass while
     * the thing it guards was broken.
     *
     * str_contains() on the path: "/act_111/adsets" and "/act_111/adcreatives"
     * both contain "/act_111/ads", so the ad assertion matched the ad set
     * request instead and passed while the ad's own status was free to be
     * anything. Caught by flipping createAd's line on its own and watching
     * nothing go red.
     *
     * And the first matching POST: validateAdSet() posts to /adsets first with
     * execution_options=validate_only, so the ad set assertion was reading the
     * dry run's payload and never saw what was actually created.
     */
    private function sentTo(string $path): ?array
    {
        foreach (Http::recorded() as [$request]) {
            /** @var ClientRequest $request */
            if ($request->method() !== 'POST') {
                continue;
            }

            if (filled($request->data()['execution_options'] ?? null)) {
                continue;
            }

            if (str_ends_with(rtrim((string) parse_url($request->url(), PHP_URL_PATH), '/'), $path)) {
                return $request->data();
            }
        }

        return null;
    }

    public function test_the_campaign_is_created_paused(): void
    {
        $this->publish();

        $sent = $this->sentTo('/act_111/campaigns');

        $this->assertNotNull($sent, 'Nothing was sent to the campaigns endpoint.');
        $this->assertSame('PAUSED', $sent['status'] ?? null, 'the campaign was created live');
    }

    /**
     * The ad set is created active, under the paused campaign.
     *
     * Asked for by media buying: they launch, review in Ads Manager, and switch
     * the campaign on. Three levels to switch on meant a campaign that read as
     * started and delivered nothing. Meta gates a tree on its campaign, so an
     * active ad set under a paused campaign spends nothing and reports
     * CAMPAIGN_PAUSED - the guarantee is unchanged, it is just enforced at one
     * level instead of three.
     */
    public function test_the_ad_set_is_created_active_under_the_paused_campaign(): void
    {
        $this->publish();

        $sent = $this->sentTo('/act_111/adsets');

        $this->assertNotNull($sent, 'Nothing was sent to the adsets endpoint.');
        $this->assertSame('ACTIVE', $sent['status'] ?? null);
    }

    /** And every level is paused again when the config asks for it. */
    public function test_the_ad_set_is_created_paused_when_the_pause_level_is_all(): void
    {
        config(['platforms.guardrails.publish_pause_level' => 'all']);

        $this->publish();

        $sent = $this->sentTo('/act_111/adsets');

        $this->assertSame('PAUSED', $sent['status'] ?? null, 'the ad set ignored publish_pause_level=all');
    }

    /** The ad, the same way and for the same reason. */
    public function test_the_ad_is_created_active_under_the_paused_campaign(): void
    {
        $this->publish();

        $sent = $this->sentTo('/act_111/ads');

        $this->assertNotNull($sent, 'Nothing was sent to the ads endpoint.');
        $this->assertSame('ACTIVE', $sent['status'] ?? null);
    }

    public function test_the_ad_is_created_paused_when_the_pause_level_is_all(): void
    {
        config(['platforms.guardrails.publish_pause_level' => 'all']);

        $this->publish();

        $this->assertSame('PAUSED', $this->sentTo('/act_111/ads')['status'] ?? null);
    }

    /**
     * The invariant, stated on its own because it is the whole guarantee.
     *
     * Whatever the children are created as, nothing a publish creates may be
     * able to spend. The campaign is the only level that has to be paused for
     * that to hold, and it is not configurable.
     */
    public function test_the_campaign_is_paused_whatever_the_children_are(): void
    {
        foreach (['campaign', 'all'] as $level) {
            config(['platforms.guardrails.publish_pause_level' => $level]);

            Http::fake();
            $this->publish();

            $this->assertSame(
                'PAUSED',
                $this->sentTo('/act_111/campaigns')['status'] ?? null,
                "the campaign was created live with publish_pause_level={$level}",
            );
        }
    }
}
