<?php

namespace Tests\Feature;

use App\Campaigns\CampaignImporter;
use App\Campaigns\Publisher;
use App\Models\Asset;
use App\Models\AssetPlatformRef;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use RuntimeException;
use Tests\TestCase;

/**
 * Two things media buying found, both in the same place: a campaign somebody
 * else is holding.
 *
 * The first is the restart. pause() stops at the campaign, which is enough to
 * halt delivery and deliberately leaves the ad sets and ads as they were.
 * activate() sets every one of them ACTIVE. Those two together mean a buyer who
 * turned off a losing ad by hand in Ads Manager, paused the campaign from the
 * chat and restarted it later got that ad spending again, with nothing said.
 * Mohsin described that workflow in as many words - campaigns paused and
 * restarted months later on Danny's instructions - so it is a question of when
 * rather than whether.
 *
 * The first activation still has to set everything live: publishing creates the
 * whole tree PAUSED, so a campaign-only activation would deliver nothing and
 * read as a slow start. The two cases are told apart by asking Meta what the ad
 * sets say, because activated_at cannot - Publisher nulls it on pause, so a
 * paused campaign and one that never ran look identical locally.
 *
 * The second is adoption. Looking a campaign up by external id alone handed back
 * whatever row held that id, no matter who owned it, along with its objective,
 * budget, targeting and ad copy. adoptGoogle() has always refused that; the Meta
 * branch never asked.
 */
class RestartingACampaignDoesNotResurrectPausedAdsTest extends TestCase
{
    use RefreshDatabase;

    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.max_daily_budget' => 1000,
            // Pinned, because the dev server sets it and six tests have already
            // passed here and failed there for want of this line.
            'platforms.guardrails.paused' => false,
        ]);
    }

    // ------------------------------------------------------------- the restart

    /**
     * The defect: a restart that puts a hand-paused ad back to work.
     *
     * The ad set reads ACTIVE on Meta, which is only true of a campaign that has
     * run, so there is nothing here for activate() to start except the campaign.
     */
    public function test_a_restart_does_not_touch_the_ads_under_a_campaign_that_has_run(): void
    {
        $campaign = $this->publishedCampaign();

        $this->fakeMeta(adSetStatus: 'ACTIVE');

        $this->activate($campaign);

        $written = $this->statusWrites();

        $this->assertSame(['id:120252047635070626'], $written->keys()->all());
        $this->assertSame('ACTIVE', $written->get('id:120252047635070626'));
    }

    /** And the first activation still starts the whole tree, which is the point of it. */
    public function test_a_first_activation_still_starts_every_level(): void
    {
        $campaign = $this->publishedCampaign();

        $this->fakeMeta(adSetStatus: 'PAUSED');

        $this->activate($campaign);

        $written = $this->statusWrites();

        foreach (['ad-1', 'adset-1', '120252047635070626'] as $id) {
            $this->assertSame('ACTIVE', $written->get('id:'.$id), "{$id} was never set live");
        }
    }

    /**
     * One live ad set out of two is enough to leave the others alone.
     *
     * The reading is about the campaign, not each ad set: if anything under it is
     * running then somebody has already chosen these statuses, and a second ad set
     * sitting paused next to a live one is the likeliest thing they chose.
     */
    public function test_one_live_ad_set_is_enough_to_leave_the_rest_as_they_are(): void
    {
        $campaign = $this->publishedCampaign();

        $campaign->adSets()->create([
            'position' => 2,
            'name' => 'UK test',
            'external_adset_id' => 'adset-2',
            'status' => 'published',
        ]);

        Http::fake([
            '*/adsets*' => Http::response(['data' => [
                ['id' => 'adset-1', 'status' => 'ACTIVE'],
                ['id' => 'adset-2', 'status' => 'PAUSED'],
            ]]),
            '*' => Http::response(['success' => true]),
        ]);

        $this->activate($campaign);

        $this->assertSame(['id:120252047635070626'], $this->statusWrites()->keys()->all());
    }

    /**
     * A read that fails starts everything, which is the harmless direction.
     *
     * A campaign that will not start is somebody watching a spinner and asking
     * why; an ad restarted that they had paused is one line in Ads Manager. With
     * no evidence either way, take the behaviour this has always had.
     */
    public function test_an_unreadable_campaign_is_started_in_full(): void
    {
        $campaign = $this->publishedCampaign();

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

        $this->activate($campaign);

        $this->assertSame('ACTIVE', $this->statusWrites()->get('id:ad-1'), 'a failed read stopped the activation');
    }

    /** And pausing is still the campaign and nothing else. */
    public function test_pausing_still_stops_at_the_campaign(): void
    {
        $campaign = $this->publishedCampaign();
        $campaign->update(['activated_at' => now()]);

        $this->fakeMeta(adSetStatus: 'ACTIVE');

        app(Publisher::class)->pause($campaign->fresh(), 'tester');

        $this->assertSame(['id:120252047635070626' => 'PAUSED'], $this->statusWrites()->all());
    }

    // ------------------------------------------------------------- the adoption

    /** The defect: somebody else's campaign, handed over on the strength of its id. */
    public function test_a_campaign_another_user_manages_is_not_adopted(): void
    {
        $theirs = $this->publishedCampaign();

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('already managed by another user');

        app(CampaignImporter::class)->adopt(
            (string) $theirs->external_campaign_id,
            User::factory()->create(),
        );
    }

    /** Nothing about it is read out either, which is what the refusal is protecting. */
    public function test_the_refusal_happens_before_anything_is_read(): void
    {
        $theirs = $this->publishedCampaign();

        Http::fake(['*' => Http::response(['success' => true])]);

        $refused = null;

        try {
            app(CampaignImporter::class)->adopt(
                (string) $theirs->external_campaign_id,
                User::factory()->create(),
            );
        } catch (RuntimeException $e) {
            $refused = $e;
        }

        // Asserted out here rather than with a fail() in the try, because
        // PHPUnit's AssertionFailedError extends RuntimeException - the catch
        // above swallows it, and this test passed against the defect until a
        // mutation run said so.
        $this->assertNotNull($refused, 'somebody else\'s campaign was adopted');
        Http::assertNothingSent();
        $this->assertSame(1, Campaign::where('external_campaign_id', $theirs->external_campaign_id)->count());
    }

    /** And the owner still gets their own row back rather than a second one. */
    public function test_the_owner_adopting_twice_still_gets_the_same_row(): void
    {
        $mine = $this->publishedCampaign();

        $again = app(CampaignImporter::class)->adopt(
            (string) $mine->external_campaign_id,
            User::find($mine->user_id),
        );

        $this->assertSame($mine->id, $again->id);
    }

    // ------------------------------------------------------------------ fixtures

    private function fakeMeta(string $adSetStatus): void
    {
        Http::fake([
            '*/adsets*' => Http::response(['data' => [['id' => 'adset-1', 'status' => $adSetStatus]]]),
            '*' => Http::response(['success' => true]),
        ]);
    }

    private function activate(Campaign $campaign): void
    {
        app(Publisher::class)->activate(
            app(Publisher::class)->proposeActivation($campaign->fresh(), 'tester'),
            'tester',
        );
    }

    /**
     * What was written where, keyed by the object it was written to.
     *
     * Reads are excluded by looking only at requests carrying a status, so the
     * ad set read this now makes does not show up as a write. The ids are kept
     * prefixed because a campaign id is all digits and PHP would turn the key
     * into an int, which then fails an identity comparison against the string
     * the column holds.
     *
     * @return Collection<string,string>
     */
    private function statusWrites(): Collection
    {
        return collect(Http::recorded())
            ->filter(fn (array $pair): bool => ($pair[0]->data()['status'] ?? null) !== null)
            ->mapWithKeys(fn (array $pair): array => [
                'id:'.basename(parse_url($pair[0]->url(), PHP_URL_PATH) ?: '') => $pair[0]->data()['status'],
            ]);
    }

    private function publishedCampaign(): Campaign
    {
        $user = User::factory()->create();
        $this->actingAs($user);

        $campaign = Campaign::create([
            'user_id' => $user->id,
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'published',
            'objective' => 'OUTCOME_TRAFFIC',
            'ad_account_id' => 'act_111',
            'page_id' => 'page-1',
            'landing_url' => 'https://example.com/offer',
            'budget' => 25,
            'budget_mode' => 'daily',
            'currency' => 'USD',
            'locations' => ['countries' => ['US']],
            'placements' => ['facebook'],
            'special_ad_categories' => ['NONE'],
            'utm' => '',
            'external_campaign_id' => '120252047635070626',
            'external_ids' => ['campaign_id' => '120252047635070626', 'adset_id' => 'adset-1'],
        ]);

        $campaign->primaryAdSet->update(['external_adset_id' => 'adset-1', 'status' => 'published']);

        $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,
            'external_ad_id' => 'ad-1',
            'external_creative_id' => 'creative-1',
            'status' => 'published',
        ]);

        return $campaign->fresh();
    }
}
