<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Cache;

use App\Scolarite\Domain\Model\Evaluation\ClassStatistics;
use App\Scolarite\Domain\Model\Evaluation\EvaluationId;
use App\Scolarite\Domain\Repository\EvaluationStatisticsRepository;
use Override;
use Psr\Cache\CacheItemPoolInterface;

final readonly class CachingEvaluationStatisticsRepository implements EvaluationStatisticsRepository
{
    public function __construct(
        private EvaluationStatisticsRepository $inner,
        private CacheItemPoolInterface $cache,
    ) {
    }

    #[Override]
    public function save(EvaluationId $evaluationId, ClassStatistics $statistics): void
    {
        $this->inner->save($evaluationId, $statistics);
        $this->cache->deleteItem($this->cacheKey($evaluationId));
    }

    #[Override]
    public function findByEvaluation(EvaluationId $evaluationId): ?ClassStatistics
    {
        $key = $this->cacheKey($evaluationId);
        $item = $this->cache->getItem($key);

        if ($item->isHit()) {
            /** @var ClassStatistics|null $cached */
            $cached = $item->get();

            return $cached;
        }

        $stats = $this->inner->findByEvaluation($evaluationId);

        $item->set($stats);
        $this->cache->save($item);

        return $stats;
    }

    #[Override]
    public function delete(EvaluationId $evaluationId): void
    {
        $this->inner->delete($evaluationId);
        $this->cache->deleteItem($this->cacheKey($evaluationId));
    }

    private function cacheKey(EvaluationId $evaluationId): string
    {
        return 'eval_stats_' . $evaluationId;
    }
}
