<?php

namespace MintyPHP\Service\Import;

class ImportStateStoreService
{
    private const SESSION_KEY = 'admin_imports_v1';
    private const STATE_TTL_SECONDS = 7200;

    public function __construct(private readonly ImportTempFileService $importTempFileService)
    {
    }

    /**
     * @param array<string, mixed> $state
     */
    public function setState(string $token, array $state): void
    {
        if (!isset($_SESSION[self::SESSION_KEY]) || !is_array($_SESSION[self::SESSION_KEY])) {
            $_SESSION[self::SESSION_KEY] = [];
        }
        $_SESSION[self::SESSION_KEY][$token] = $state;
    }

    /**
     * @return array<string, mixed>|null
     */
    public function getState(string $token): ?array
    {
        $token = trim($token);
        if ($token === '') {
            return null;
        }

        $all = $_SESSION[self::SESSION_KEY] ?? [];
        if (!is_array($all)) {
            return null;
        }

        $state = $all[$token] ?? null;
        if (!is_array($state)) {
            return null;
        }

        $createdAt = (int) ($state['created_at'] ?? 0);
        if ($createdAt > 0 && (time() - $createdAt) > self::STATE_TTL_SECONDS) {
            $this->importTempFileService->delete((string) ($state['path'] ?? ''));
            $this->clearState($token);
            return null;
        }

        return $state;
    }

    public function clearState(string $token): void
    {
        if (!isset($_SESSION[self::SESSION_KEY]) || !is_array($_SESSION[self::SESSION_KEY])) {
            return;
        }
        unset($_SESSION[self::SESSION_KEY][$token]);
    }
}

