<?php

namespace Tests\Feature;

use App\Services\Dashboard\DashboardTablePresenter;
use App\Services\Filters\StickyDateRange;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\FeatureTestTrait;
use Config\Services;

/**
 * ADC-190: a metric-header sort must be able to return the new top 10 as JSON
 * instead of redirecting the whole dashboard. A plain POST still redirects.
 *
 * Run with the feature config:
 *   php8.2 -d newrelic.enabled=0 -d newrelic.daemon.dont_launch=3 \
 *     vendor/bin/phpunit -c phpunit.feature.xml tests/feature/DashboardTableSortTest.php
 */
final class DashboardTableSortTest extends CIUnitTestCase
{
    use FeatureTestTrait;

    /** Throwaway advertiser id — never a real account, so the table comes back empty. */
    private const ADV = 999999992;

    private const START = '2026-02-03';
    private const END   = '2026-02-19';

    private int $obLevel = 0;

    /** @var array<string,mixed> */
    private array $cookieBackup = [];

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

        Services::injectMock('response', Services::response(null, false));

        $this->cookieBackup = service('superglobals')->getGlobalArray('cookie');
        $this->obLevel      = ob_get_level();
        StickyDateRange::resetRequestCache();
    }

    protected function tearDown(): void
    {
        service('superglobals')->setGlobalArray('cookie', $this->cookieBackup);
        while (ob_get_level() > $this->obLevel) {
            ob_end_clean();
        }
        StickyDateRange::resetRequestCache();
        parent::tearDown();
    }

    /** @return array<string,mixed> */
    private function session(array $extra = []): array
    {
        return [
            'logged_in' => 1,
            'adv_id'    => self::ADV,
            'user_id'   => self::ADV,
            'role'      => 'admin',
        ] + $extra;
    }

    /** @param array<string,mixed> $extra */
    private function postSort(string $kpi, bool $ajax, array $extraSession = [])
    {
        $call = $this->withSession($this->session($extraSession));
        if ($ajax) {
            $call = $call->withHeaders(['X-Requested-With' => 'XMLHttpRequest']);
        }

        return $call->post('dashboard', [
            'dashboard_action' => 'set_table_sort',
            'sort_kpi'         => $kpi,
            'date_start'       => self::START,
            'date_end'         => self::END,
        ]);
    }

    public function testAjaxSortReturnsTheNewTopTenWithoutRedirecting(): void
    {
        $response = $this->postSort('spend', true);

        $response->assertOK();
        $response->assertNotRedirect();
        $this->assertStringContainsString(
            'application/json',
            $response->response()->getHeaderLine('Content-Type')
        );

        $payload = json_decode($response->getJSON(), true);
        $this->assertSame('spend', $payload['activeSort']);
        $this->assertSame('Spend', $payload['activeSortLabel']);
        $this->assertIsArray($payload['rows']);
        $this->assertIsArray($payload['totals']);
        $this->assertSame('spend', session()->get(DashboardTablePresenter::SESSION_SORT_KEY));
    }

    public function testAnUnknownSortKpiDoesNotChangeTheSession(): void
    {
        $response = $this->postSort('not-a-kpi', true, [
            DashboardTablePresenter::SESSION_SORT_KEY => 'clicks',
        ]);

        $response->assertOK();
        $payload = json_decode($response->getJSON(), true);
        $this->assertSame('clicks', $payload['activeSort']);
        $this->assertSame('clicks', session()->get(DashboardTablePresenter::SESSION_SORT_KEY));
    }

    public function testANormalPostStillRedirects(): void
    {
        $response = $this->postSort('spend', false);

        $response->assertRedirect();
        $this->assertSame('spend', session()->get(DashboardTablePresenter::SESSION_SORT_KEY));
    }
}
