<?php

declare(strict_types=1);

namespace App\Controller;

use DateTimeImmutable;
use DateTimeInterface;
use Doctrine\DBAL\Connection;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;
use Throwable;

class HealthCheckController extends AbstractController
{
    #[Route('/api/health', name: 'api_health', methods: ['GET'])]
    public function __invoke(Connection $connection): JsonResponse
    {
        $dbOk = false;

        try {
            $start = hrtime(true);
            $connection->executeQuery('SELECT 1');
            $dbLatency = round((hrtime(true) - $start) / 1e6, 1);
            $dbOk      = true;
        } catch (Throwable) {
            $dbLatency = null;
        }

        $healthy = $dbOk;
        $data    = ['status' => $healthy ? 'ok' : 'degraded'];

        if ($this->isGranted('ROLE_ADMIN')) {
            $version     = '0.0.0';
            $versionFile = $this->getParameter('kernel.project_dir').'/VERSION';
            if (file_exists($versionFile)) {
                $version = trim(file_get_contents($versionFile));
            }

            $data += [
                'version'   => $version,
                'timestamp' => new DateTimeImmutable()->format(DateTimeInterface::ATOM),
                'php'       => PHP_VERSION,
                'checks'    => [
                    'database' => [
                        'status'     => $dbOk ? 'ok' : 'down',
                        'latency_ms' => $dbLatency,
                    ],
                ],
                'memory_mb' => round(memory_get_usage(true) / 1024 / 1024, 1),
            ];
        }

        return $this->json($data, $healthy ? 200 : 503);
    }
}
