<?php

namespace App\Tests\Shared;

use App\Shared\Controller\HealthController;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\TestCase;
use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

/**
 * probe سلامت redis نباید هنگام افتادن redis لاگ warning در app_log بریزد:
 * HealthController باید logger این pool را با NullLogger خنثی کند و صرفاً وضعیت را برگرداند.
 */
class HealthControllerTest extends TestCase
{
    private function em(): EntityManagerInterface
    {
        $conn = $this->createMock(Connection::class);
        $conn->method('executeQuery'); // SELECT 1 → موفق
        $em = $this->createMock(EntityManagerInterface::class);
        $em->method('getConnection')->willReturn($conn);

        return $em;
    }

    public function testSilencesLoggerOnPool(): void
    {
        $pool = new class implements CacheItemPoolInterface, LoggerAwareInterface {
            public ?LoggerInterface $logger = null;
            public function setLogger(LoggerInterface $logger): void { $this->logger = $logger; }
            public function getItem($key): CacheItemInterface { throw new \RuntimeException('redis down'); }
            public function getItems(array $keys = []): iterable { return []; }
            public function hasItem($key): bool { return false; }
            public function clear(): bool { return true; }
            public function deleteItem($key): bool { return true; }
            public function deleteItems(array $keys): bool { return true; }
            public function save(CacheItemInterface $item): bool { return true; }
            public function saveDeferred(CacheItemInterface $item): bool { return true; }
            public function commit(): bool { return true; }
        };

        $controller = new HealthController($this->em(), $pool);

        // logger فوراً در constructor خنثی می‌شود
        $this->assertInstanceOf(NullLogger::class, $pool->logger);

        // redis افتاده → degraded + 503، بدون throw
        $response = $controller();
        $this->assertSame(503, $response->getStatusCode());
        $body = json_decode($response->getContent(), true);
        $this->assertSame('degraded', $body['status']);
        $this->assertSame('error', $body['checks']['redis']);
        $this->assertSame('ok', $body['checks']['database']);
    }
}
