<?php

namespace Tests\Feature;

use App\Agent\Choices;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Platforms\Platforms;
use App\Campaigns\PublishGate;
use App\Campaigns\Publishing\MetaPublisher;
use App\Models\Campaign;
use App\Models\User;
use App\Services\Meta\AdSetSpec;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

/**
 * The ad set optimises toward an event the pixel actually fires.
 *
 * It was never asked. The event came from the objective alone: leads meant LEAD,
 * sales meant PURCHASE, and whether that pixel had ever seen such an event was
 * not consulted. Meta accepts it either way, so the campaign spends against
 * something it can never observe and the result reads as underdelivery. Every
 * number looks plausible, which is what makes it the hardest of these to find.
 *
 * Kaushal's campaign 120252047635070626 is the live case: pixel
 * 1017787001151608 fires PageView 102 times and Subscribe once, has never fired
 * Lead, and the ad set is asking Meta to optimise toward LEAD.
 */
class TheEventTheCampaignOptimisesTowardTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

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

        $this->seedVerifiedCountries();

        config([
            'platforms.meta.token' => 'test-token',
            'platforms.guardrails.allowed_ad_accounts' => ['meta:*'],
        ]);

        $this->actingAs(User::factory()->create());
        app(Workspace::class)->bindTo('conv-conversion-event');
    }

    /** @param array<string,int> $events */
    private function pixelFiring(array $events): void
    {
        $buckets = collect($events)
            ->map(fn (int $count, string $name): array => [
                'aggregation' => 'event',
                'data' => [['value' => $name, 'count' => $count]],
            ])
            ->values()
            ->all();

        Http::fake([
            '*/stats*' => Http::response(['data' => $buckets]),
            '*' => Http::response(['data' => []]),
        ]);
    }

    private function campaign(array $attributes = []): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Lucos leads',
            'platform' => 'meta',
            'status' => 'draft',
            'objective' => 'OUTCOME_LEADS',
            'ad_account_id' => 'act_1950320145707342',
            'pixel_id' => '1017787001151608',
            'locations' => ['countries' => ['US']],
            ...$attributes,
        ]);

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

        return $campaign;
    }

    private function tool(array $arguments = []): array
    {
        $result = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t) => $t->name() === 'campaign__choose_conversion_event')
            ->handle(new Request($arguments));

        return json_decode((string) $result, true);
    }

    // ------------------------------------------------------ the actual defect

    /**
     * The objective's default is called out when the pixel has never fired it.
     *
     * This is the whole tool. Kaushal's exact pixel and objective.
     */
    public function test_a_default_event_the_pixel_never_fired_is_flagged(): void
    {
        $this->pixelFiring(['PageView' => 102, 'Subscribe' => 1]);
        $this->campaign();

        $result = $this->tool();

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertTrue($result['default_never_fired'] ?? false, 'a LEAD default on this pixel was not flagged');
        $this->assertStringContainsString('never fired', $result['note']);
    }

    /**
     * And the events it has fired are what is offered - minus any the ad set
     * cannot take.
     *
     * This asserted PageView was offered, and offering it is the production
     * defect: Meta's custom_event_type enum has no PAGE_VIEW member, so the one
     * thing a buyer could click was the one thing that could not publish. It
     * reached Mohsin on 7 Oct on a pixel that fires nothing else, and the ad set
     * was refused after the campaign object already existed.
     *
     * 102 firings against Subscribe's 1, deliberately: the event the pixel fires
     * most is still not offered, because how often it fires says nothing about
     * whether Meta will optimise toward it.
     */
    public function test_the_events_the_pixel_fired_are_offered(): void
    {
        $this->pixelFiring(['PageView' => 102, 'Subscribe' => 1]);
        $this->campaign();

        $this->tool();

        $offered = collect(app(Choices::class)->all())->firstWhere('field', 'conversion_event');

        $this->assertNotNull($offered, 'nothing was put on screen');
        $values = collect($offered['options'])->pluck('value');

        // Every event a leads campaign accepts, not just what this pixel fired.
        $this->assertTrue($values->contains('Subscribe'), 'a fired event is missing');
        $this->assertTrue($values->contains('Lead'), 'an unfired but valid event is missing');
        $this->assertFalse($values->contains('PageView'), 'PAGE_VIEW is not a Meta enum member');

        // The history survives as a hint, which is the part that was worth keeping.
        $subscribe = collect($offered['options'])->firstWhere('value', 'Subscribe');
        $lead = collect($offered['options'])->firstWhere('value', 'Lead');
        $this->assertStringContainsString('fired', (string) $subscribe['hint']);
        $this->assertStringContainsString('not fired', (string) $lead['hint']);

        // And a custom event can be typed.
        $this->assertTrue($offered['allow_other'] ?? false, 'a custom event cannot be entered');
    }

    /** A pixel that does fire the default says nothing alarming. */
    public function test_a_default_the_pixel_does_fire_is_not_flagged(): void
    {
        $this->pixelFiring(['Lead' => 34, 'PageView' => 900]);
        $this->campaign();

        $result = $this->tool();

        $this->assertArrayNotHasKey('default_never_fired', $result);
        $this->assertStringNotContainsString('never fired', $result['note']);
    }

    /**
     * The suggested badge goes on the objective's own event, when it has fired.
     *
     * The unbadged event was PageView, which is no longer offered at all - Meta's
     * enum has no member for it - so this read the badge off null. Subscribe
     * stands in: an event the pixel fires, the ad set accepts, and the objective
     * did not ask for.
     */
    public function test_the_objectives_event_is_marked_suggested(): void
    {
        $this->pixelFiring(['Lead' => 34, 'Subscribe' => 900]);
        $this->campaign();

        $this->tool();

        $options = collect(app(Choices::class)->all())->firstWhere('field', 'conversion_event')['options'];

        $this->assertSame('Suggested', collect($options)->firstWhere('value', 'Lead')['badge']);
        $this->assertNull(collect($options)->firstWhere('value', 'Subscribe')['badge']);
    }

    // ------------------------------------------------------------- the answer

    /** Choosing one stores Meta's enum, not the pixel's spelling. */
    public function test_the_chosen_event_is_stored_as_the_enum(): void
    {
        $this->pixelFiring(['PageView' => 102, 'Subscribe' => 1]);
        $campaign = $this->campaign();

        $result = $this->tool(['conversion_event' => 'Subscribe']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('SUBSCRIBE', $result['conversion_event']);
        $this->assertSame('SUBSCRIBE', $campaign->refresh()->conversion_event);
    }

    /**
     * Counts come back with it, because that is what justified the choice.
     *
     * Counted against Subscribe rather than PageView, which can no longer be
     * chosen. PageView stays in the pixel's history with the larger count, so the
     * count being reported is demonstrably the chosen event's and not simply the
     * busiest one.
     */
    public function test_the_reply_says_how_often_it_fired(): void
    {
        $this->pixelFiring(['PageView' => 102, 'Subscribe' => 57]);
        $this->campaign();

        $this->assertSame(57, $this->tool(['conversion_event' => 'Subscribe'])['times_fired']);
    }

    /**
     * An event the pixel has never fired is allowed, and warned about.
     *
     * This asserted a refusal, and the refusal was the blocker: a leads campaign
     * on a pixel that has only ever fired PageView had no answer it could give,
     * and every attempt to say "use Lead anyway" was turned down. Meta accepts an
     * event with no history; what it lacks is anything to optimise against, which
     * is a delivery problem the buyer is entitled to weigh for themselves.
     */
    public function test_an_event_the_pixel_never_fired_is_allowed_with_a_warning(): void
    {
        $this->pixelFiring(['PageView' => 102, 'Subscribe' => 1]);
        $campaign = $this->campaign();

        $result = $this->tool(['conversion_event' => 'Lead']);

        $this->assertTrue($result['ok'] ?? false, $result['error'] ?? '');
        $this->assertSame('LEAD', $campaign->fresh()->conversion_event);
        $this->assertSame(0, $result['times_fired']);
        $this->assertStringContainsString('has not fired on this pixel yet', $result['warning']);
    }

    /** PAGE_VIEW is still refused, because Meta has no such enum member. */
    public function test_page_view_is_still_refused_however_often_it_fired(): void
    {
        $this->pixelFiring(['PageView' => 151]);
        $this->campaign();

        $this->assertFalse($this->tool(['conversion_event' => 'PageView'])['ok']);
    }

    /** Case is not the buyer's problem. */
    public function test_the_event_name_is_matched_case_insensitively(): void
    {
        $this->pixelFiring(['Subscribe' => 1]);
        $campaign = $this->campaign();

        $this->assertTrue($this->tool(['conversion_event' => 'subscribe'])['ok']);
        $this->assertSame('SUBSCRIBE', $campaign->refresh()->conversion_event);
    }

    /**
     * A custom event is a real answer and becomes OTHER.
     *
     * Meta has no enum member for it, and refusing would make a site that
     * tracks its own events unable to optimise toward any of them.
     */
    public function test_a_custom_event_is_published_as_other(): void
    {
        $this->pixelFiring(['SubscribedToPlan' => 12]);
        $campaign = $this->campaign();

        $result = $this->tool(['conversion_event' => 'SubscribedToPlan']);

        $this->assertSame('OTHER', $result['conversion_event']);
        $this->assertSame('event:SubscribedToPlan', $campaign->refresh()->conversion_event);
        $this->assertSame('SubscribedToPlan', $result['custom_event_str']);
        $this->assertStringContainsString('custom event', $result['note']);
    }

    // ------------------------------------------------------------ the refusals

    /**
     * A pixel with no history is not a refusal.
     *
     * One installed an hour ago has fired nothing, and the objective's default
     * is then the only thing anyone can go on. Refusing here would stop a new
     * advertiser from finishing at all.
     */
    /**
     * A pixel with no history is offered the full list, not given a default.
     *
     * This used to write the objective's default and move on, recorded as
     * FALLBACK, because there was nothing to put on screen - the list was built
     * from fired events and an empty history produced an empty list, so the flow
     * would otherwise ask forever with nothing to click. Now the list does not
     * depend on history, so the honest thing is to ask: a value written with no
     * evidence is exactly what the FALLBACK source existed to apologise for.
     */
    public function test_a_pixel_with_no_history_is_offered_the_full_list(): void
    {
        $this->pixelFiring([]);
        $campaign = $this->campaign();

        $result = $this->tool();

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

        $offered = collect(app(Choices::class)->all())->firstWhere('field', 'conversion_event');
        $values = collect($offered['options'] ?? [])->pluck('value');

        $this->assertTrue($values->contains('Lead'), 'nothing was offered for a pixel with no history');
        $this->assertTrue($values->count() > 1, 'only one event was offered');
        $this->assertNull($campaign->refresh()->conversion_event, 'a value was written without being chosen');
        $this->assertTrue($result['default_never_fired'] ?? false, 'the default having no history was not flagged');
    }

    /** A traffic campaign has no event to optimise toward, and is told so. */
    public function test_a_traffic_objective_has_nothing_to_choose(): void
    {
        $this->pixelFiring(['PageView' => 102]);
        $this->campaign(['objective' => 'OUTCOME_TRAFFIC']);

        $result = $this->tool();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('does not optimise toward a pixel event', $result['error']);
    }

    /** The pixel comes first, since it is where the events are read from. */
    public function test_a_campaign_with_no_pixel_is_refused(): void
    {
        $this->pixelFiring(['PageView' => 102]);
        $this->campaign(['pixel_id' => null]);

        $result = $this->tool();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('Choose the pixel first', $result['error']);
    }

    /** Google counts conversions its own way and has no part in this. */
    public function test_a_google_campaign_is_refused(): void
    {
        $this->pixelFiring(['PageView' => 102]);
        $this->campaign(['platform' => 'google', 'ad_account_id' => '3460855874', 'objective' => 'LEADS']);

        $this->assertFalse($this->tool()['ok']);
    }

    // ------------------------------------------------- what reaches the publisher

    /**
     * A custom event the pixel fired is a row, and it is what gets published.
     *
     * Sales would otherwise offer only Purchase, Lead and the other standard
     * commerce events. attestpathcustom is on the dataset and has to be choosable.
     * Purchase has never fired, so the suggestion is the event that has.
     */
    public function test_a_fired_custom_event_is_offered_and_published_with_its_name(): void
    {
        $this->pixelFiring([
            'PageView' => 100,
            'Lead' => 12,
            'attestpathcustom' => 40,
        ]);
        $campaign = $this->campaign([
            'objective' => 'OUTCOME_SALES',
            'optimization_goal' => 'OFFSITE_CONVERSIONS',
            'budget' => 10,
            'budget_mode' => 'daily',
            'page_id' => 'page-1',
        ]);

        $result = $this->tool();

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

        $options = collect(app(Choices::class)->all())->firstWhere('field', 'conversion_event')['options'];
        $values = collect($options)->pluck('value');

        $this->assertTrue($values->contains('event:attestpathcustom'));
        $this->assertFalse($values->contains('PageView'));
        $this->assertSame('Suggested', collect($options)->firstWhere('value', 'event:attestpathcustom')['badge']);
        $this->assertNull(collect($options)->firstWhere('value', 'Purchase')['badge']);
        $this->assertLessThan(
            $values->search('Purchase'),
            $values->search('event:attestpathcustom'),
        );

        $chosen = $this->tool(['conversion_event' => 'event:attestpathcustom']);

        $this->assertTrue($chosen['ok'], $chosen['error'] ?? '');
        $this->assertSame('event:attestpathcustom', $campaign->refresh()->conversion_event);
        $this->assertSame(40, $chosen['times_fired']);

        $promoted = $this->adSetFor($campaign)->promotedObject();

        $this->assertSame([
            'pixel_id' => '1017787001151608',
            'custom_event_type' => 'OTHER',
            'custom_event_str' => 'attestpathcustom',
        ], $promoted);
        $this->assertFalse(
            collect(app(PublishGate::class)->soundness($campaign))
                ->contains(fn (string $problem): bool => str_contains($problem, 'optimised toward')),
        );
    }

    /** A custom conversion is published by id, not as a generic OTHER event. */
    public function test_a_custom_conversion_is_offered_and_published_by_id(): void
    {
        Http::fake([
            '*/stats*' => Http::response(['data' => [
                ['aggregation' => 'event', 'data' => [['value' => 'Lead', 'count' => 2]]],
            ]]),
            '*/customconversions*' => Http::response(['data' => [
                [
                    'id' => '998877',
                    'name' => 'Pricing signup',
                    'custom_event_type' => 'OTHER',
                    'is_archived' => false,
                    'last_fired_time' => '2026-10-01T00:00:00+0000',
                    'pixel' => ['id' => '1017787001151608'],
                ],
                [
                    'id' => '111',
                    'name' => 'Old signup',
                    'is_archived' => true,
                    'pixel' => ['id' => '1017787001151608'],
                ],
                [
                    'id' => '222',
                    'name' => 'Other pixel',
                    'is_archived' => false,
                    'pixel' => ['id' => '999'],
                ],
            ]]),
            '*' => Http::response(['data' => []]),
        ]);

        $campaign = $this->campaign([
            'objective' => 'OUTCOME_SALES',
            'optimization_goal' => 'OFFSITE_CONVERSIONS',
            'budget' => 10,
            'budget_mode' => 'daily',
            'page_id' => 'page-1',
        ]);

        $this->tool();

        $values = collect(app(Choices::class)->all())
            ->firstWhere('field', 'conversion_event')['options'];

        $this->assertTrue(collect($values)->pluck('value')->contains('conversion:998877'));
        $this->assertFalse(collect($values)->pluck('value')->contains('conversion:111'));
        $this->assertFalse(collect($values)->pluck('value')->contains('conversion:222'));

        $chosen = $this->tool(['conversion_event' => 'conversion:998877']);

        $this->assertTrue($chosen['ok'], $chosen['error'] ?? '');
        $this->assertSame('conversion:998877', $campaign->refresh()->conversion_event);
        $this->assertSame([
            'pixel_id' => '1017787001151608',
            'custom_conversion_id' => '998877',
        ], $this->adSetFor($campaign)->promotedObject());
    }

    /** A custom-conversion read that fails does not hide the pixel's events. */
    public function test_a_failed_custom_conversion_read_still_offers_pixel_events(): void
    {
        Http::fake([
            '*/stats*' => Http::response(['data' => [
                ['aggregation' => 'event', 'data' => [['value' => 'Lead', 'count' => 3]]],
            ]]),
            '*/customconversions*' => Http::response([
                'error' => ['message' => 'permission denied', 'code' => 200],
            ], 400),
            '*' => Http::response(['data' => []]),
        ]);

        $this->campaign();

        $result = $this->tool();

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $values = collect(app(Choices::class)->all())
            ->firstWhere('field', 'conversion_event')['options'];
        $this->assertTrue(collect($values)->pluck('value')->contains('Lead'));
    }

    /**
     * The chosen event is what is published, not the objective's default.
     *
     * Through MetaPublisher's own ad set builder, because asserting on an
     * AdSetSpec built by hand passes whether the publisher reads the column or
     * keeps deriving the event, which is how this test was first written: the
     * whole fix could be reverted with the suite still green.
     */
    public function test_the_publisher_sends_the_chosen_event(): void
    {
        $campaign = $this->campaign([
            'conversion_event' => 'SUBSCRIBE',
            'optimization_goal' => 'OFFSITE_CONVERSIONS',
            'budget' => 10,
            'budget_mode' => 'daily',
            'page_id' => 'page-1',
        ]);

        $spec = $this->adSetFor($campaign);

        $this->assertSame('SUBSCRIBE', $spec->promotedObject()['custom_event_type']);
    }

    /** And the objective's default still applies when nobody chose. */
    public function test_the_publisher_falls_back_to_the_objectives_event(): void
    {
        $campaign = $this->campaign([
            'conversion_event' => null,
            'optimization_goal' => 'OFFSITE_CONVERSIONS',
            'budget' => 10,
            'budget_mode' => 'daily',
            'page_id' => 'page-1',
        ]);

        $this->assertSame('LEAD', $this->adSetFor($campaign)->promotedObject()['custom_event_type']);
    }

    /**
     * The publisher's own ad set builder, which is the line that was wrong.
     *
     * Takes the ad set row now, since there can be more than one. The campaign's
     * own conversion_event is its first ad set's, which is the one passed here.
     */
    private function adSetFor(Campaign $campaign): AdSetSpec
    {
        Http::preventStrayRequests();
        $publisher = app(MetaPublisher::class);

        $method = new \ReflectionMethod($publisher, 'adSet');
        $method->setAccessible(true);

        return $method->invoke($publisher, $campaign, $campaign->primaryAdSet, 'campaign-1');
    }

    /**
     * Only Meta gets the row and the step.
     *
     * LinkedInRules::conversionEvent() maps objectives to events for its own
     * publisher while having no step to choose one and no tool that accepts one,
     * so gating either on that method gives LinkedIn a question nothing can
     * answer and a panel row that stays grey for the life of the campaign.
     */
    public function test_only_metas_flow_asks_for_a_conversion_event(): void
    {
        $asks = fn (string $platform): bool => collect(app(Platforms::class)
            ->for($platform)
            ->steps())
            ->contains(fn (array $step): bool => ($step['key'] ?? null) === 'conversion_event');

        $this->assertTrue($asks('meta'));
        $this->assertFalse($asks('linkedin'), 'LinkedIn has no tool for this and must not be asked');
        $this->assertFalse($asks('google'));
    }
}
