<?php

declare(strict_types=1);

namespace SHServ\Integrations\GAuth\Store;

use GNexus\GAuth\Contract\PkceStoreInterface;

final class SessionPkceStore implements PkceStoreInterface
{
    private const SESSION_KEY = 'gauth_pkce';

    public function __construct()
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            @session_start();
        }
    }

    public function put(string $state, string $verifier, \DateTimeImmutable $expiresAt): void
    {
        $_SESSION[self::SESSION_KEY][$state] = [
            'verifier' => $verifier,
            'expires_at' => $expiresAt->format(\DateTimeInterface::ATOM),
        ];
    }

    public function get(string $state): ?string
    {
        $record = $_SESSION[self::SESSION_KEY][$state] ?? null;

        if (!is_array($record)) {
            return null;
        }

        try {
            $expiresAt = new \DateTimeImmutable($record['expires_at']);
        } catch (\Exception $e) {
            unset($_SESSION[self::SESSION_KEY][$state]);
            return null;
        }

        if ($expiresAt < new \DateTimeImmutable()) {
            unset($_SESSION[self::SESSION_KEY][$state]);
            return null;
        }

        return isset($record['verifier']) ? (string) $record['verifier'] : null;
    }

    public function forget(string $state): void
    {
        unset($_SESSION[self::SESSION_KEY][$state]);
    }
}
