<?php

namespace Openguru\OpenCartFramework\Telegram;

use Openguru\OpenCartFramework\Cache\CacheInterface;

class TelegramBotStateManager
{
    private CacheInterface $cache;

    public function __construct(CacheInterface $cache)
    {
        $this->cache = $cache;
    }

    public function getStateKey(string $userId, string $chatId): string
    {
        return md5('tg-state-' . $userId . '-' . $chatId);
    }

    public function setState(string $handler, string $userId, string $chatId, array $data = []): void
    {
        $payload = [
            'handler' => $handler,
            'user_id' => $userId,
            'chat_id' => $chatId,
            'data' => $data,
        ];

        $this->cache->set($this->getStateKey($userId, $chatId), $payload, 120);
    }

    public function getState(string $userId, string $chatId): ?array
    {
        return $this->cache->get($this->getStateKey($userId, $chatId));
    }

    public function hasState(string $userId, string $chatId): bool
    {
        return ! empty($this->cache->get($this->getStateKey($userId, $chatId)));
    }

    public function clearState(string $userId, string $chatId): void
    {
        $this->cache->delete($this->getStateKey($userId, $chatId));
    }

    public function getCurrentStateCommandHandler(string $userId, string $chatId): string
    {
        $state = $this->getState($userId, $chatId);

        return $state['handler'];
    }
}
