<?php

namespace Tests\Unit\Dashboard;

use App\Services\Dashboard\DashboardFilters;
use App\Services\Filters\StickyDateRange;
use DateInterval;
use DateTimeImmutable;
use PHPUnit\Framework\TestCase;

/**
 * DashboardFilters after the range moved out to StickyDateRange.
 *
 * The negative assertions are the point of this file: the class used to hold the range in
 * flashdata and was documented "deliberately NOT sticky". A revert that quietly restores
 * that path would leave two half-persisting stores in play and reproduce the original bug,
 * so it fails here instead.
 */
final class DashboardFiltersStickyTest extends TestCase
{
    /**
     * The whole controller wiring rests on this: the store's payload can be handed
     * straight to normalize() because normalize() rebuilds from an explicit key list.
     */
    public function testNormalizeDropsTheStoresExtraKeys(): void
    {
        $out = DashboardFilters::normalize([
            'date_start' => '2026-04-01',
            'date_end'   => '2026-04-07',
            'preset'     => 'last7',
        ]);

        $this->assertSame(['date_start', 'date_end'], array_keys($out));
        $this->assertSame('2026-04-01', $out['date_start']);
        $this->assertSame('2026-04-07', $out['date_end']);
    }

    public function testAStorePayloadRoundTripsThroughNormalize(): void
    {
        $sticky = StickyDateRange::normalize(
            ['date_start' => '2026-04-01', 'date_end' => '2026-04-07', 'preset' => 'custom'],
            DashboardFilters::defaults()
        );

        $out = DashboardFilters::normalize($sticky);

        $this->assertSame($sticky['date_start'], $out['date_start']);
        $this->assertSame($sticky['date_end'], $out['date_end']);
    }

    /** Still 7 inclusive days ending yesterday — the store's tier-3 fallback. */
    public function testDefaultsAreSevenDaysEndingYesterday(): void
    {
        $end   = (new DateTimeImmutable('today'))->sub(new DateInterval('P1D'));
        $start = $end->sub(new DateInterval('P6D'));

        $defaults = DashboardFilters::defaults();

        $this->assertSame($start->format('Y-m-d'), $defaults['date_start']);
        $this->assertSame($end->format('Y-m-d'), $defaults['date_end']);
    }

    public function testTheFlashBasedApiIsGone(): void
    {
        $this->assertFalse(
            method_exists(DashboardFilters::class, 'fromFlash'),
            'fromFlash() re-introduces a per-redirect range beside the shared store'
        );
        $this->assertFalse(
            method_exists(DashboardFilters::class, 'saveForNextRequest'),
            'saveForNextRequest() re-introduces the flash path'
        );
        $this->assertFalse(
            defined(DashboardFilters::class . '::SESSION_KEY'),
            'SESSION_KEY was the flash bucket; the range lives in StickyDateRange now'
        );
    }
}
