<?php

declare(strict_types=1);

namespace SeoScope\Security;

final class CsrfToken
{
    private const SESSION_KEY = '_seoscope_install_csrf';

    public static function sessionKey(): string
    {
        return self::SESSION_KEY;
    }

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

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

    public static function clear(): void
    {
        unset($_SESSION[self::SESSION_KEY]);
    }
}
