<?php

declare(strict_types=1);

namespace SHServ\Integrations\GAuth\Store;

use GNexus\GAuth\Contract\StateStoreInterface;

final class SessionStateStore implements StateStoreInterface
{
    private const SESSION_KEY = 'gauth_state';

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

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

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

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

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

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

        return true;
    }

    public function getContext(string $state): array
    {
        if (!$this->has($state)) {
            return [];
        }

        return $_SESSION[self::SESSION_KEY][$state]['context'] ?? [];
    }

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