<?php

namespace App\Shared\Controller;

use Doctrine\ORM\EntityManagerInterface;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\NullLogger;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;

class HealthController
{
    public function __construct(
        private readonly EntityManagerInterface $em,
        private readonly CacheItemPoolInterface $healthPool,
    ) {
        // probe سلامت نباید هنگام افتادن redis لاگ warning تولید کند؛ logger این pool را خنثی می‌کنیم.
        if ($this->healthPool instanceof LoggerAwareInterface) {
            $this->healthPool->setLogger(new NullLogger());
        }
    }

    #[Route('/health', methods: ['GET'])]
    public function __invoke(): JsonResponse
    {
        $checks = [];
        $status = 'ok';

        try {
            $this->em->getConnection()->executeQuery('SELECT 1');
            $checks['database'] = 'ok';
        } catch (\Throwable) {
            $checks['database'] = 'error';
            $status = 'degraded';
        }

        try {
            $this->healthPool->getItem('health_check');
            $checks['redis'] = 'ok';
        } catch (\Throwable) {
            $checks['redis'] = 'error';
            $status = 'degraded';
        }

        return new JsonResponse([
            'status'    => $status,
            'checks'    => $checks,
            'timestamp' => time(),
        ], $status === 'ok' ? 200 : 503);
    }
}
