<?php

namespace MintyPHP\Service\Import;

use MintyPHP\Http\SessionStoreInterface;

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

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

    /**
     * @param array<string, mixed> $state
     */
    public function setState(string $token, array $state): void
    {
        $states = $this->sessionStore->get(self::SESSION_KEY, []);
        if (!is_array($states)) {
            $states = [];
        }
        $states[$token] = $state;
        $this->sessionStore->set(self::SESSION_KEY, $states);
    }

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

        $all = $this->sessionStore->get(self::SESSION_KEY, []);
        if (!is_array($all)) {
            return null;
        }

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

        // Lazy expiry: clean up the temp file and session entry when the state is accessed after TTL.
        $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
    {
        $states = $this->sessionStore->get(self::SESSION_KEY, []);
        if (!is_array($states)) {
            return;
        }

        unset($states[$token]);
        $this->sessionStore->set(self::SESSION_KEY, $states);
    }
}
