<?php

namespace MintyPHP\Tests\Unit\Support;

use MintyPHP\Support\Flash;
use PHPUnit\Framework\TestCase;

final class FlashTest extends TestCase
{
    private array $sessionBackup = [];

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

        $this->sessionBackup = $_SESSION ?? [];
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        $_SESSION = [];
    }

    protected function tearDown(): void
    {
        $_SESSION = $this->sessionBackup;

        if (session_status() === PHP_SESSION_ACTIVE) {
            session_write_close();
        }

        parent::tearDown();
    }

    public function testConsumeForScopesReturnsMatchingAndLeavesOthers(): void
    {
        Flash::success('Saved', 'admin/users', 'saved');
        Flash::error('Global error', null, 'global_error');
        Flash::info('Other scope', 'admin/roles', 'other_scope');

        $consumed = Flash::consumeForScopes(['admin/users', 'admin/users?active=1']);

        $consumedKeys = array_column($consumed, 'key');
        self::assertSame(['saved', 'global_error'], $consumedKeys);

        $remaining = Flash::peek();
        self::assertCount(1, $remaining);
        self::assertSame('other_scope', $remaining[0]['key'] ?? null);
    }

    public function testConsumeForScopesMatchesPathAndPathWithQueryUnion(): void
    {
        Flash::success('From path', 'admin/users', 'path_only');
        Flash::success('From path query', 'admin/users?tab=profile', 'path_query');

        $consumed = Flash::consumeForScopes(['admin/users', 'admin/users?tab=profile']);
        $consumedKeys = array_column($consumed, 'key');

        self::assertSame(['path_only', 'path_query'], $consumedKeys);
        self::assertSame([], Flash::peek());
    }

    public function testConsumeForScopesSupportsEmptyRootScope(): void
    {
        Flash::error('Root scoped', '', 'root_scope');

        $consumed = Flash::consumeForScopes(['']);

        self::assertCount(1, $consumed);
        self::assertSame('root_scope', $consumed[0]['key'] ?? null);
        self::assertSame([], Flash::peek());
    }

    public function testConsumeForScopesIsIdempotentPerRequestPath(): void
    {
        Flash::success('Saved once', 'admin/settings', 'settings_saved');

        $firstConsume = Flash::consumeForScopes(['admin/settings']);
        $secondConsume = Flash::consumeForScopes(['admin/settings']);

        self::assertCount(1, $firstConsume);
        self::assertCount(0, $secondConsume);
    }
}
