<?php

namespace Tests\Feature;

use App\Models\User;
use App\Services\Meta\Meta;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

/**
 * "Has this pixel ever fired Lead?" was being asked about yesterday.
 *
 * pixelEvents() called {pixel}/stats with aggregation alone - no start_time, no
 * end_time, no paging - so Meta applied its own default window of roughly a day
 * and we read the first page of it, then reported the result as the pixel's whole
 * history.
 *
 * Checked against the live API on 8 Oct, pixel 1337654058454168:
 *
 *   bare call      -> hourly buckets from the previous day, PageView only
 *   30-day window  -> PageView 2254, Lead 22, and paging.next still set
 *
 * So the chat told buyers the pixel had never fired Lead, refused to optimise
 * toward it, and sent them to Events Manager to install an event that was already
 * live and had fired 22 times. Four turns of that on arb-dev, after which the
 * campaign published on LEAD anyway through the objective's silent default.
 *
 * It also accounts for an earlier dead end I had written off as a quirk of the
 * endpoint: /stats answering {"data":[]} for autoautomotive_clck while its
 * last_fired_time was two days old. The endpoint was never the problem.
 */
class APixelsHistoryIsReadOverThirtyDaysTest 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' => ['act_111'],
            'platforms.guardrails.paused' => false,
        ]);

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

    /** @param  list<array<string,mixed>>  $buckets */
    private function bucket(string $event, int $count): array
    {
        return ['aggregation' => 'event', 'data' => [['value' => $event, 'count' => $count]]];
    }

    public function test_the_window_is_asked_for_rather_than_left_to_meta(): void
    {
        Http::fake(['*' => Http::response(['data' => [$this->bucket('PageView', 3)]])]);

        app(Meta::class)->on(null, 'tester')->pixelEvents('1337654058454168');

        $request = collect(Http::recorded())->first()[0];
        parse_str((string) parse_url($request->url(), PHP_URL_QUERY), $query);

        $this->assertArrayHasKey('start_time', $query, 'no window was requested, so Meta picks about a day');
        $this->assertArrayHasKey('end_time', $query);

        $span = ((int) $query['end_time'] - (int) $query['start_time']) / 86400;

        $this->assertGreaterThan(29, $span, 'the window is narrower than Events Manager shows');
        $this->assertLessThan(31, $span, 'a wider window costs calls against the shared hourly budget');
    }

    /**
     * The event that was being missed.
     *
     * Lead on page two, PageView on page one, mirroring the live shape where the
     * rare event is the one that matters and the common one crowds it out.
     */
    public function test_an_event_on_a_later_page_is_still_counted(): void
    {
        $page = 0;

        Http::fake(function () use (&$page) {
            $page++;

            return $page === 1
                ? Http::response([
                    'data' => [$this->bucket('PageView', 2254)],
                    'paging' => ['cursors' => ['after' => 'CURSOR']],
                ])
                : Http::response(['data' => [$this->bucket('Lead', 22)]]);
        });

        $events = app(Meta::class)->on(null, 'tester')->pixelEvents('1337654058454168');

        $this->assertSame(22, $events['Lead'] ?? null, 'Lead was on page two and was dropped');
        $this->assertSame(2254, $events['PageView'] ?? null);
        $this->assertSame(2, $page, 'the second page was never fetched');
    }

    /** Most frequent first, because that ordering is what the chooser badges. */
    public function test_the_counts_are_ordered_by_frequency(): void
    {
        Http::fake(['*' => Http::response(['data' => [
            $this->bucket('Lead', 22),
            $this->bucket('PageView', 2254),
        ]])]);

        $events = app(Meta::class)->on(null, 'tester')->pixelEvents('1337654058454168');

        $this->assertSame(['PageView', 'Lead'], array_keys($events));
    }

    /**
     * A cursor that never settles does not loop forever.
     *
     * Each page is a call against the hourly budget, and its account-less bucket
     * is shared with the Page and ad-account lists the launch flow needs - a
     * runaway here locks choose_page out for an hour, which is exactly how an
     * unrelated 50-call loop blocked a publish on 8 Oct.
     */
    public function test_a_cursor_that_never_ends_is_capped(): void
    {
        $calls = 0;

        Http::fake(function () use (&$calls) {
            $calls++;

            return Http::response([
                'data' => [$this->bucket('PageView', 1)],
                'paging' => ['cursors' => ['after' => 'ALWAYS']],
            ]);
        });

        app(Meta::class)->on(null, 'tester')->pixelEvents('1337654058454168');

        $this->assertLessThanOrEqual(4, $calls, 'the paging loop is unbounded');
        $this->assertGreaterThan(1, $calls, 'it stopped before following a single cursor');
    }

    /** An empty history is still ordinary, not an error. */
    public function test_a_pixel_with_no_history_returns_nothing(): void
    {
        Http::fake(['*' => Http::response(['data' => []])]);

        $this->assertSame([], app(Meta::class)->on(null, 'tester')->pixelEvents('1337654058454168'));
    }
}
