<?php

namespace App\Payment\Service;

use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;

class CircuitBreakerService
{
    private const FAIL_THRESHOLD = 3;
    private const OPEN_TTL       = 300; // 5 minutes

    public function __construct(private readonly CacheInterface $cache) {}

    public function isOpen(string $gateway): bool
    {
        $item = $this->cache->getItem('cb_open_' . $gateway);
        return $item->isHit();
    }

    public function recordFailure(string $gateway): void
    {
        $countKey = 'cb_fail_' . $gateway;
        $item     = $this->cache->getItem($countKey);
        $count    = ($item->isHit() ? (int) $item->get() : 0) + 1;

        $item->set($count)->expiresAfter(self::OPEN_TTL);
        $this->cache->save($item);

        if ($count >= self::FAIL_THRESHOLD) {
            $openItem = $this->cache->getItem('cb_open_' . $gateway);
            $openItem->set(true)->expiresAfter(self::OPEN_TTL);
            $this->cache->save($openItem);
        }
    }

    public function recordSuccess(string $gateway): void
    {
        $this->cache->deleteItem('cb_fail_' . $gateway);
        $this->cache->deleteItem('cb_open_' . $gateway);
    }
}
