<?php

declare(strict_types=1);

namespace SeoScope\Auth;

final class AdminCsrf
{
    private const SESSION_KEY = '_seoscope_admin_csrf';

    public static function token(): string
    {
        if (empty($_SESSION[self::SESSION_KEY])) {
            $_SESSION[self::SESSION_KEY] = bin2hex(random_bytes(32));
        }
        return $_SESSION[self::SESSION_KEY];
    }

    public static function validate(mixed $submitted): bool
    {
        if (!is_string($submitted)) {
            return false;
        }
        $submitted = trim($submitted);
        if ($submitted === '') {
            return false;
        }
        $expected = $_SESSION[self::SESSION_KEY] ?? null;
        return is_string($expected) && hash_equals($expected, $submitted);
    }

    public static function refresh(): string
    {
        $_SESSION[self::SESSION_KEY] = bin2hex(random_bytes(32));
        return $_SESSION[self::SESSION_KEY];
    }
}
