<?php

namespace Tests\Feature;

use App\Campaigns\Objectives;
use App\Campaigns\PublishGate;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

/**
 * PAGE_VIEW is not a member of Meta's custom_event_type enum, on any objective.
 *
 * The guard for "this objective's ad set will not take that event" already
 * existed and already covered the chooser, the validator and the publish gate,
 * because all three ask Objectives::acceptsEventType(). It only held for
 * OUTCOME_SALES, the one objective whose accepted list we hold verbatim; for
 * every other objective acceptedEventTypes() returns null, which means unknown,
 * and unknown correctly reads as "not evidence against anything".
 *
 * That reasoning is right and it is also why PAGE_VIEW got through. The refusal
 * is not the objective's, it is the enum's: there is no such member to accept.
 *
 *   5 Oct, OUTCOME_TRAFFIC, act_1238155271384134, api_calls 172
 *   7 Oct, OUTCOME_LEADS,   act_1950320145707342, api_calls 549
 *
 * Both arrived from ads_create_ad_set after ads_create_campaign had already
 * returned an id, so both left a campaign on the account with no ad set under
 * it. The second reached a buyer whose pixel has fired nothing but PageView, so
 * the chat offered it, it was the only thing on screen, and it could not work.
 *
 * The two errors do not even read alike. The first came back as VALIDATION with
 * Meta's sentence in it; the second as {"error_category":"INTERNAL",
 * "is_retryable":true}, which is a permanent refusal wearing a transient one's
 * clothes. Retrying it three times would have failed three times, so the fix
 * belongs here, before anything is created, and not in the retry policy.
 */
class AnEventMetaHasNoEnumForIsRefusedEarlyTest extends TestCase
{
    use RefreshDatabase;

    // ------------------------------------------------------------ the rule

    /**
     * Refused on every objective, including the four with no known list.
     *
     * OUTCOME_SALES would have refused it already. The other four are the
     * regression.
     */
    public function test_page_view_is_refused_on_every_objective(): void
    {
        $objectives = ['OUTCOME_SALES', 'OUTCOME_LEADS', 'OUTCOME_TRAFFIC',
            'OUTCOME_ENGAGEMENT', 'OUTCOME_AWARENESS'];

        foreach ($objectives as $objective) {
            $this->assertFalse(
                Objectives::acceptsEventType($objective, 'PAGE_VIEW'),
                $objective.' still accepts PAGE_VIEW',
            );
        }
    }

    /** Including when the objective itself is unknown. */
    public function test_page_view_is_refused_with_no_objective_at_all(): void
    {
        $this->assertFalse(Objectives::acceptsEventType(null, 'PAGE_VIEW'));
    }

    /**
     * And nothing else became collateral.
     *
     * The change sits in front of the unknown-list rule, so it would be easy to
     * make it swallow everything: a blanket false there refuses every event on
     * four of the five objectives, which is the same bug pointing the other way
     * and much harder to notice, because the symptom is a buyer who cannot
     * finish rather than one who cannot publish.
     */
    public function test_an_unknown_list_still_accepts_what_it_did_before(): void
    {
        foreach (['LEAD', 'PURCHASE', 'SUBSCRIBE', 'CONTENT_VIEW', 'OTHER'] as $event) {
            $this->assertTrue(
                Objectives::acceptsEventType('OUTCOME_LEADS', $event),
                $event.' is now refused on a leads campaign',
            );
        }
    }

    /** A sales campaign keeps refusing what it refused before. */
    public function test_the_known_list_is_unchanged(): void
    {
        $this->assertTrue(Objectives::acceptsEventType('OUTCOME_SALES', 'PURCHASE'));
        $this->assertFalse(Objectives::acceptsEventType('OUTCOME_SALES', 'SUBSCRIBE'));
    }

    /**
     * The pixel vocabulary is deliberately untouched.
     *
     * A pixel does fire PageView and eventType() reporting otherwise would be a
     * different wrong answer. What changed is whether an ad set may optimise
     * toward it, which is a separate question asked by a separate method.
     */
    public function test_a_pixel_firing_page_view_is_still_named_honestly(): void
    {
        $this->assertSame('PAGE_VIEW', Objectives::eventType('PageView'));
    }

    // --------------------------------- and the refusal has a way out on screen

    // ------------------------------------------------ and the gate uses it

    /**
     * The publish gate blocks it, which is what stops the campaign being created.
     *
     * PublishGate::conversionEvent() asks the same function, so this needs no
     * second fix - but it is the assertion that matters, because the gate is the
     * last thing between a stored PAGE_VIEW and ads_create_campaign.
     */
    public function test_the_publish_gate_blocks_a_stored_page_view(): void
    {
        $user = User::factory()->create();
        $this->actingAs($user);

        $brief = Brief::create([
            'user_id' => $user->id,
            'conversation_id' => 'conv-page-view',
            'landing_url' => 'https://attestpath.com/soc2',
            'budget' => 20,
            'budget_mode' => 'daily',
        ]);

        $campaign = Campaign::create([
            'user_id' => $user->id,
            'brief_id' => $brief->id,
            'name' => 'Attestpath SOC 2',
            'platform' => 'meta',
            'status' => 'draft',
            'currency' => 'USD',
            'ad_account_id' => 'act_1950320145707342',
            'objective' => 'OUTCOME_LEADS',
            'pixel_id' => '1337654058454168',
            'conversion_event' => 'PAGE_VIEW',
        ]);

        $blockers = collect(app(PublishGate::class)->check($campaign->fresh()))
            ->flatten()->filter()->map(fn (mixed $v): string => (string) $v);

        // "PageView", not PAGE_VIEW: the gate says it in the pixel vocabulary the
        // buyer sees in Events Manager, which is the point of eventName().
        $this->assertTrue(
            $blockers->contains(fn (string $blocker): bool => str_contains($blocker, 'PageView')
                && str_contains($blocker, 'cannot be optimised toward')),
            'the gate let PAGE_VIEW through: '.$blockers->implode(' | '),
        );
    }

    /**
     * Characterisation, not an assertion that this is right.
     *
     * The gate's sentence ends "It accepts %s there.", and only OUTCOME_SALES has
     * a list to put in it, so on the other four objectives it renders with the
     * names missing and the gap left in. Refusing PAGE_VIEW everywhere is what
     * makes that reachable: before this change the only event that could get this
     * far was one a sales list refused, and the sales list is the one we hold.
     *
     * Left exactly as it was by instruction - PublishGate is not to be changed -
     * so this records the state rather than fixing it. ChooseConversionEvent
     * refuses PAGE_VIEW before it can be stored, which is why this is cosmetic
     * for new campaigns; it is reachable on a campaign that already has
     * PAGE_VIEW on it, and prod campaign 10 does.
     *
     * If the gap is ever closed, this test should fail and be deleted. That is
     * the point of it.
     */
    public function test_the_gates_sentence_still_has_the_gap_in_it(): void
    {
        $user = User::factory()->create();
        $this->actingAs($user);

        $campaign = Campaign::create([
            'user_id' => $user->id,
            'name' => 'Attestpath SOC 2',
            'platform' => 'meta',
            'status' => 'draft',
            'currency' => 'USD',
            'ad_account_id' => 'act_1950320145707342',
            'objective' => 'OUTCOME_LEADS',
            'conversion_event' => 'PAGE_VIEW',
        ]);

        $blockers = collect(app(PublishGate::class)->check($campaign->fresh()))
            ->flatten()->filter()->map(fn (mixed $v): string => (string) $v);

        $this->assertTrue(
            $blockers->contains(fn (string $blocker): bool => str_contains($blocker, 'It accepts  there.')),
            'the gap has been closed, so delete this test: '.$blockers->implode(' | '),
        );
    }
}
