<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Publisher;
use App\Campaigns\Publishing\MetaPublisher;
use App\Models\Asset;
use App\Models\AssetPlatformRef;
use App\Models\Campaign;
use App\Models\CampaignAdSet;
use App\Models\Decision;
use App\Models\Location;
use App\Models\PlatformLocation;
use App\Models\TargetingSet;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use PHPUnit\Framework\Attributes\DataProvider;
use RuntimeException;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

/**
 * A second ad set under a campaign that is already running.
 *
 * Testing a second audience, country or budget against the same offer is most of
 * what media buying is, and the product could not do it. A campaign held one ad
 * set's settings in its own columns, so the second one's targeting had nowhere
 * to live; the ad set existed only as an id in external_ids. Buyers went to Ads
 * Manager instead, and from that point our copy of the campaign and Meta's
 * disagreed with nothing to say so.
 *
 * What these pin: it reaches Meta under the live campaign, it arrives paused
 * while its parent is spending, its own targeting and budget are what is sent,
 * the live campaign is not touched, and a refusal leaves a draft to fix rather
 * than litter.
 */
class AddingAnAdSetToALiveCampaignTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

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

        $this->seedVerifiedCountries();

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

        $workspace = app(Workspace::class);
        $workspace->bindTo('conv-add-ad-set');
        $workspace->ownedBy(auth()->user());

        config([
            'platforms.meta.mcp.enabled' => false,
            // Named, not '*': the wildcard is not honoured by the guardrail.
            'platforms.guardrails.allowed_ad_accounts' => ['act_111'],
            'platforms.guardrails.max_daily_budget' => 500,
        ]);
    }

    /**
     * A campaign already on Meta, with one published ad set and one ad.
     */
    private function liveCampaign(array $attributes = []): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'published',
            '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'],
            'external_campaign_id' => '120111',
            'external_ids' => ['campaign_id' => '120111', 'adset_id' => '120222'],
            ...$attributes,
        ]);

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

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

        return $campaign->fresh();
    }

    private function withAnAd(Campaign $campaign): Campaign
    {
        $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([
            'ad_set_id' => $campaign->primaryAdSet->id,
            '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();
    }

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

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

        return json_decode((string) $tool->handle(new Request($arguments)), true);
    }

    /** Meta answers every create with a new id, and records what was asked. */
    private function fakeMeta(): void
    {
        Http::fake([
            '*' => Http::sequence()
                ->push(['id' => 'adset-new'])
                ->push(['id' => 'creative-new'])
                ->push(['id' => 'ad-new'])
                ->whenEmpty(Http::response(['success' => true])),
        ]);
    }

    public function test_it_creates_the_ad_set_on_the_platform_under_the_live_campaign(): void
    {
        $campaign = $this->withAnAd($this->liveCampaign());
        $this->fakeMeta();

        $result = $this->addAdSet(['countries' => ['GB'], 'budget' => 15, 'name' => 'UK test']);

        $this->assertTrue($result['ok'] ?? false, $result['error'] ?? '');

        $added = $campaign->adSets()->where('position', 2)->first();

        $this->assertNotNull($added, 'No second ad set row was created.');
        $this->assertSame('adset-new', $added->external_adset_id);
        $this->assertSame('UK test', $added->name);
        $this->assertSame(['GB'], $added->locations['countries']);
        $this->assertSame(15.0, (float) $added->budget);

        // Sent under the campaign that already exists, not a new one.
        $bodies = collect(Http::recorded())->map(fn (array $pair): string => (string) $pair[0]->body());

        $this->assertTrue(
            $bodies->contains(fn (string $body): bool => str_contains($body, '120111')),
            'the new ad set was not attached to the live campaign',
        );
    }

    #[DataProvider('unsupportedPlaceCases')]
    public function test_unsupported_places_are_reported_by_the_gate(string $key, array $criteria): void
    {
        $this->liveCampaign(['locations' => [
            'countries' => ['US'],
            $key => $criteria,
        ]]);
        $this->fakeMeta();

        $result = $this->addAdSet(['name' => 'Imported places']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('must be reselected', $result['error']);
        $this->assertNotEmpty($result['still_needed']);
        $this->assertSame('draft', CampaignAdSet::findOrFail($result['ad_set_id'])->status);
        $this->assertDatabaseMissing('decisions', ['action' => 'add_ad_set']);
        Http::assertNothingSent();
    }

    /** @return array<string, array{string, array}> */
    public static function unsupportedPlaceCases(): array
    {
        return [
            'imported places' => ['meta_geo_locations', ['countries' => ['US'], 'cities' => [['key' => '2427173']]]],
            'legacy city' => ['cities', ['Chicago']],
            'legacy region' => ['regions', ['Illinois']],
        ];
    }

    #[DataProvider('restrictedAudienceCases')]
    public function test_campaign_audience_selections_block_new_ad_sets_before_approval(string $operation, bool $mcp): void
    {
        $campaign = $this->liveCampaign();
        $this->saveAudienceRestriction($campaign, $operation);
        config(['platforms.meta.mcp.enabled' => $mcp, 'platforms.meta.mcp.token' => 'test-mcp-token']);
        Http::fake();

        $result = $this->addAdSet(['countries' => ['GB'], 'name' => 'Second audience']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('audience inclusions or exclusions', $result['error']);
        $this->assertNotEmpty($result['still_needed']);
        $this->assertDatabaseMissing('decisions', ['action' => 'add_ad_set']);
        $this->assertNull(CampaignAdSet::findOrFail($result['ad_set_id'])->external_adset_id);
        Http::assertNothingSent();
    }

    /** @return array<string, array{string, bool}> */
    public static function restrictedAudienceCases(): array
    {
        return [
            'include with Graph' => ['include', false], 'exclude with Graph' => ['exclude', false],
            'include with MCP' => ['include', true], 'exclude with MCP' => ['exclude', true],
        ];
    }

    private function saveAudienceRestriction(Campaign $campaign, string $operation = 'exclude'): void
    {
        TargetingSet::factory()->forCampaign($campaign)->create(['options' => ['meta_audiences' => [[
            'id' => '700', 'name' => 'Existing customers', 'subtype' => 'WEBSITE',
            'pixel_id' => '800', 'account_id' => '111', 'operation' => $operation,
        ]]]]);
    }

    public function test_imported_audience_exclusions_block_an_ad_set_addition(): void
    {
        $this->liveCampaign(['external_ids' => [
            'campaign_id' => '120111', 'adset_id' => '120222',
            'meta_custom_audience_criteria' => [[
                'adset_id' => '120222', 'custom_audiences' => [], 'excluded_custom_audiences' => [['id' => '700']],
            ]],
        ]]);
        Http::fake();

        $result = $this->addAdSet(['countries' => ['GB']]);

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

    public function test_versioned_places_cannot_be_omitted_from_an_added_ad_set(): void
    {
        $campaign = $this->liveCampaign();
        // A city has no ISO country code of its own, and the factory's default is
        // a country, so without this the row takes a real country's code: a city
        // named "France" holding iso_code FR. locations.iso_code is globally
        // unique, so it then collided with the seeded countries at random and
        // this test failed whenever the faker happened to pick a seeded one.
        $location = Location::factory()->create([
            'type' => 'city',
            'country_code' => 'US',
            'iso_code' => null,
        ]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $location->id, 'platform' => 'meta', 'external_id' => '2427173',
            'status' => 'verified', 'verified_at' => now(),
        ]);
        TargetingSet::factory()->forCampaign($campaign)->create()->locations()->create([
            'location_id' => $location->id, 'platform_location_id' => $mapping->id,
            'kind' => 'city', 'operation' => 'include', 'country_code' => 'US', 'display_label' => 'Chicago',
        ]);
        Http::fake();

        $result = $this->addAdSet([]);

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

    public function test_empty_ad_set_places_do_not_erase_the_campaign_restriction(): void
    {
        $campaign = $this->liveCampaign(['locations' => ['countries' => ['US'], 'cities' => ['Chicago']]]);
        $adSet = $campaign->adSets()->create([
            'name' => 'Second set', 'position' => 2,
            'locations' => ['countries' => ['US'], 'cities' => []],
        ]);
        Http::fake();
        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('place restrictions');

        try {
            app(MetaPublisher::class)->addAdSet($adSet, 'tester');
        } finally {
            Http::assertNothingSent();
        }
    }

    public function test_a_restriction_added_after_review_blocks_approval(): void
    {
        $campaign = $this->liveCampaign();
        $adSet = $campaign->adSets()->create([
            'name' => 'Second set', 'position' => 2,
            'locations' => ['countries' => ['GB']], 'placements' => ['facebook'],
        ]);
        $publisher = app(Publisher::class);
        $decision = $publisher->proposeAdSet($adSet, 'tester');
        $this->assertSame('proposed', $decision->state);
        $this->saveAudienceRestriction($campaign);
        Http::fake();

        $decision = $publisher->approveAdSet($decision, 'tester');

        $this->assertSame('blocked', $decision->state);
        $this->assertStringContainsString('audience inclusions or exclusions', $decision->reason);
        Http::assertNothingSent();
    }

    public function test_the_publisher_also_refuses_to_drop_audience_restrictions(): void
    {
        $campaign = $this->liveCampaign();
        $this->saveAudienceRestriction($campaign);
        $adSet = $campaign->adSets()->create([
            'name' => 'Second set', 'position' => 2, 'locations' => ['countries' => ['GB']],
        ]);
        Http::fake();
        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('audience inclusions or exclusions');

        try {
            app(MetaPublisher::class)->addAdSet($adSet, 'tester');
        } finally {
            Http::assertNothingSent();
        }
    }

    /**
     * Paused, while the campaign above it is spending.
     *
     * The one case where the parent is already live, so an ad set that arrived
     * active would start spending immediately with nobody having approved that
     * it should.
     */
    public function test_the_new_ad_set_arrives_paused(): void
    {
        $this->withAnAd($this->liveCampaign());
        $this->fakeMeta();

        $this->addAdSet(['countries' => ['GB'], 'budget' => 15]);

        $sent = collect(Http::recorded())
            ->map(fn (array $pair): string => (string) $pair[0]->body())
            ->implode("\n");

        $this->assertStringContainsString('PAUSED', $sent, 'nothing asked for PAUSED');
        $this->assertStringNotContainsString('"status":"ACTIVE"', $sent);
    }

    /** The campaign and its existing ad set are left exactly as they are. */
    public function test_the_live_campaign_is_not_touched(): void
    {
        $campaign = $this->withAnAd($this->liveCampaign());
        $first = $campaign->primaryAdSet;
        $this->fakeMeta();

        $this->addAdSet(['countries' => ['GB'], 'budget' => 15]);

        $this->assertSame('120111', $campaign->fresh()->external_campaign_id);
        $this->assertSame('120222', $first->fresh()->external_adset_id);
        $this->assertSame(['US'], $first->fresh()->locations['countries']);
        $this->assertSame(20.0, (float) $campaign->fresh()->budget);
    }

    /** It is recorded as its own decision, like publishing and starting. */
    public function test_it_is_recorded_as_a_decision(): void
    {
        $this->withAnAd($this->liveCampaign());
        $this->fakeMeta();

        $this->addAdSet(['countries' => ['GB'], 'budget' => 15]);

        $decision = Decision::where('action', 'add_ad_set')->first();

        $this->assertNotNull($decision, 'nothing was recorded');
        $this->assertSame('applied', $decision->state);
        $this->assertSame('campaign_ad_set', $decision->subject_type);
    }

    /**
     * An unpublished campaign is refused, because its ad sets go out with it.
     *
     * Not a failure to fix: adding one before publishing is simply part of the
     * campaign, and saying so is more use than a gate reason.
     */
    public function test_an_unpublished_campaign_is_refused(): void
    {
        $campaign = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Draft', 'platform' => 'meta', 'status' => 'draft', 'currency' => 'USD',
        ]);

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

        $result = $this->addAdSet(['countries' => ['GB'], 'budget' => 15]);

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

    /**
     * A refused ad set is kept as a draft, and correcting it does not add a second.
     *
     * The alternative is a campaign collecting one abandoned draft ad set per
     * attempt, which is what happens if every call creates a row.
     */
    public function test_a_refused_ad_set_is_kept_and_reused(): void
    {
        $this->withAnAd($this->liveCampaign());

        // Faked once. A second Http::fake() leaves the first catch-all stub
        // answering, which is not what either call would really get.
        $this->fakeMeta();

        // No country, so the gate refuses it before anything is sent.
        $first = $this->addAdSet(['budget' => 15, 'countries' => []]);

        $this->assertFalse($first['ok'], 'an ad set with nowhere to run should be refused');
        Http::assertNothingSent();

        $second = $this->addAdSet(['countries' => ['GB'], 'budget' => 15]);

        $this->assertTrue($second['ok'] ?? false, $second['error'] ?? '');
        $this->assertSame(
            2,
            CampaignAdSet::count(),
            'the refused attempt left a second draft behind instead of being corrected',
        );
    }

    /**
     * An amount of its own is refused under Advantage campaign budget.
     *
     * Meta moves that money between ad sets itself and rejects an ad set budget
     * underneath it, so this is a refusal with a reason rather than a request
     * the platform throws out.
     */
    public function test_an_ad_set_budget_is_refused_under_a_campaign_budget(): void
    {
        $this->withAnAd($this->liveCampaign(['budget_level' => 'campaign', 'budget' => 100]));
        Http::fake();

        $result = $this->addAdSet(['countries' => ['GB'], 'budget' => 15]);

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

    /** And without one it is allowed, because the campaign's money covers it. */
    public function test_it_is_allowed_with_no_budget_under_a_campaign_budget(): void
    {
        $this->withAnAd($this->liveCampaign(['budget_level' => 'campaign', 'budget' => 100]));
        $this->fakeMeta();

        $result = $this->addAdSet(['countries' => ['GB']]);

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

    /** Over the ceiling is refused, the same as a campaign's own budget is. */
    public function test_an_amount_over_the_ceiling_is_refused(): void
    {
        $this->withAnAd($this->liveCampaign());
        Http::fake();

        $result = $this->addAdSet(['countries' => ['GB'], 'budget' => 5000]);

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

    /**
     * Unstated targeting follows the campaign rather than widening.
     *
     * "Another ad set, same places" is an ordinary ask, and defaulting to
     * everybody on a campaign deliberately narrowed to one country would be a
     * wider audience than anyone chose.
     */
    public function test_unstated_countries_follow_the_campaign(): void
    {
        $this->withAnAd($this->liveCampaign());
        $this->fakeMeta();

        $result = $this->addAdSet(['budget' => 15]);

        $this->assertTrue($result['ok'] ?? false, $result['error'] ?? '');
        $this->assertSame(['US'], CampaignAdSet::where('position', 2)->firstOrFail()->locations['countries']);
    }
}
