<?php

namespace Tests\Feature;

use App\Agent\Choices;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Objectives;
use App\Campaigns\PublishGate;
use App\Models\Campaign;
use App\Models\User;
use App\Services\Meta\Meta;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Tools\Request;
use Mockery;
use Tests\TestCase;

/**
 * A pixel firing an event does not mean the ad set will take it.
 *
 * Found on production on 5 Oct, publishing from the chat to AutoAutomotive. The
 * campaign was sales, the pixel had fired PageView six times and nothing else,
 * so the chooser offered PageView, it was picked, and the gate passed it.
 * ads_create_campaign then succeeded and ads_create_ad_set was refused:
 *
 *   custom_event_type "PAGE_VIEW" is not valid. Did you mean "PDP_VIEW"?
 *   Valid commerce values: PURCHASE, INITIATED_CHECKOUT, ADD_TO_CART,
 *   CONTENT_VIEW, ADD_TO_WISHLIST, ADD_PAYMENT_INFO, SEARCH, LEAD.
 *
 * The campaign object already existed by then, and the rollback could not
 * remove it, so the cost of offering an event Meta refuses is a stranded
 * campaign on a live account - not a refused request.
 *
 * Two vocabularies, three places. A pixel reports what it fired, in pixel
 * spelling. Objectives::EVENT_TYPE translates that to the ad set enum, which it
 * does correctly. Nothing asked the third question: whether this objective's ad
 * set accepts that enum value at all.
 */
class AnEventTheAdSetCannotTakeIsNotOfferedTest extends TestCase
{
    use RefreshDatabase;

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

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

        $workspace = app(Workspace::class);
        $workspace->bindTo('conv-accepted-events');
        $workspace->ownedBy(auth()->user());
    }

    private function campaign(array $attributes = []): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Allbirds',
            'platform' => 'meta',
            'status' => 'draft',
            'objective' => 'OUTCOME_SALES',
            'currency' => 'USD',
            'ad_account_id' => 'act_111',
            'pixel_id' => '1069023944615492',
            ...$attributes,
        ]);

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

        return $campaign;
    }

    /** @param array<string,int> $fired */
    private function pixelFiring(array $fired): void
    {
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('pixelEvents')->andReturn($fired);
        $meta->shouldReceive('customConversions')->andReturn([]);
        $meta->shouldReceive('on')->andReturnSelf();

        $this->app->instance(Meta::class, $meta);
    }

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

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

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

    // ------------------------------------------------------ what Meta told us

    public function test_a_sales_ad_set_does_not_accept_page_view(): void
    {
        $this->assertFalse(Objectives::acceptsEventType('OUTCOME_SALES', 'PAGE_VIEW'));
    }

    /** Every value Meta named in that error is accepted. */
    public function test_the_commerce_values_meta_named_are_accepted(): void
    {
        foreach ([
            'PURCHASE', 'INITIATED_CHECKOUT', 'ADD_TO_CART', 'CONTENT_VIEW',
            'ADD_TO_WISHLIST', 'ADD_PAYMENT_INFO', 'SEARCH', 'LEAD',
        ] as $type) {
            $this->assertTrue(
                Objectives::acceptsEventType('OUTCOME_SALES', $type),
                "{$type} is one Meta listed as valid and was refused.",
            );
        }
    }

    /**
     * An objective whose list nobody has recorded refuses nothing it lacks
     * evidence against.
     *
     * The alternative is inventing a list, which would block events that are in
     * fact fine. That is the same mistake in the other direction and harder to
     * notice, because it shows up as a step nobody can clear rather than as an
     * error from Meta.
     *
     * PAGE_VIEW used to be asserted here as accepted, on exactly that reasoning,
     * and production then supplied the evidence this test said it did not have.
     * Meta refused it on OUTCOME_TRAFFIC on 5 Oct and on OUTCOME_LEADS on 7 Oct:
     * "custom_event_type \"PAGE_VIEW\" is not valid. Did you mean \"PDP_VIEW\"?",
     * which is the enum rejecting a value it has no member for rather than an
     * objective declining one. So it is not an invented refusal, and refusing it
     * is not guessing at a list.
     *
     * The rule itself is unchanged, and SUBSCRIBE below is what proves it: still
     * unknown, still accepted.
     */
    public function test_an_objective_with_no_recorded_list_accepts_anything(): void
    {
        $this->assertNull(Objectives::acceptedEventTypes('OUTCOME_LEADS'));
        $this->assertTrue(Objectives::acceptsEventType('OUTCOME_LEADS', 'SUBSCRIBE'));
        $this->assertFalse(
            Objectives::acceptsEventType('OUTCOME_LEADS', 'PAGE_VIEW'),
            'Meta has no PAGE_VIEW member on any objective, and said so twice on production',
        );
    }

    // ------------------------------------------------------------ the chooser

    /** The defect: PageView was offered, because the pixel had fired it. */
    public function test_an_unacceptable_event_is_not_offered(): void
    {
        $this->campaign();
        $this->pixelFiring(['PageView' => 6, 'ViewContent' => 12]);

        $this->choose();

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

        $this->assertNotNull($offered, 'nothing was put on screen');

        $values = collect($offered['options'])->pluck('value');

        $this->assertContains('ViewContent', $values, 'an event the ad set accepts should still be offered');
        $this->assertNotContains('PageView', $values, 'PageView was offered to a sales campaign again');
    }

    /** And naming it directly is refused, in the buyer's vocabulary. */
    public function test_choosing_an_unacceptable_event_is_refused(): void
    {
        $campaign = $this->campaign();
        $this->pixelFiring(['PageView' => 6]);

        $result = $this->choose(['conversion_event' => 'PageView']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('PageView', $result['error']);
        // Said as Events Manager spells them, not as the enum.
        $this->assertStringContainsString('Purchase', $result['error']);
        $this->assertStringNotContainsString('INITIATED_CHECKOUT', $result['error']);

        $this->assertNull($campaign->fresh()->conversion_event, 'the refused event was written anyway');
    }

    /** An acceptable one is still set, so the ordinary case is untouched. */
    public function test_an_acceptable_event_is_still_set(): void
    {
        $campaign = $this->campaign();
        $this->pixelFiring(['ViewContent' => 12]);

        $result = $this->choose(['conversion_event' => 'ViewContent']);

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

    /**
     * A pixel whose only events this objective rejects is still answerable.
     *
     * This asserted a refusal. It was the blocker: a leads campaign on a
     * PageView-only pixel had nothing selectable, so the only routes out were a
     * different pixel or a different objective. The list no longer comes from the
     * pixel's history, so the objective's own events are offered and PageView is
     * simply absent from them.
     */
    public function test_a_pixel_with_nothing_usable_is_still_offered_the_objectives_events(): void
    {
        $this->campaign();
        $this->pixelFiring(['PageView' => 151]);

        $result = $this->choose();

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

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

        $this->assertNotEmpty($values, 'a PageView-only pixel was left with nothing to click');
        $this->assertFalse(collect($values)->pluck('value')->contains('PageView'));
    }

    /** A pixel that has fired nothing is asked, not defaulted. */
    public function test_a_pixel_that_has_fired_nothing_is_asked(): void
    {
        $campaign = $this->campaign();
        $this->pixelFiring([]);

        $this->assertTrue($this->choose()['ok'] ?? false);
        $this->assertNull($campaign->refresh()->conversion_event, 'a value was written without being chosen');
    }

    // --------------------------------------------------------------- the gate

    /**
     * And the gate refuses it however it got there.
     *
     * The chooser is not the only way the column gets written: a campaign
     * adopted from the platform arrives with one, and an objective changed after
     * the event was chosen leaves a pairing nobody picked.
     */
    public function test_the_gate_blocks_an_event_the_objective_cannot_take(): void
    {
        $campaign = $this->campaign(['conversion_event' => 'PAGE_VIEW']);

        $problems = app(PublishGate::class)->soundness($campaign);

        $this->assertTrue(
            collect($problems)->contains(fn (string $p): bool => str_contains($p, 'PageView')),
            'the gate let PAGE_VIEW through on a sales campaign: '.implode('; ', $problems),
        );
    }

    /** An acceptable event is not reported as a problem. */
    public function test_the_gate_allows_an_acceptable_event(): void
    {
        $campaign = $this->campaign(['conversion_event' => 'PURCHASE']);

        $this->assertFalse(
            collect(app(PublishGate::class)->soundness($campaign))
                ->contains(fn (string $p): bool => str_contains($p, 'optimised toward')),
        );
    }

    /** Nor is a campaign that has no event at all, like traffic. */
    public function test_the_gate_is_silent_with_no_event(): void
    {
        $campaign = $this->campaign(['objective' => 'OUTCOME_TRAFFIC', 'conversion_event' => null]);

        $this->assertFalse(
            collect(app(PublishGate::class)->soundness($campaign))
                ->contains(fn (string $p): bool => str_contains($p, 'optimised toward')),
        );
    }
}
