<?php

declare(strict_types=1);

namespace App\Shared\Infrastructure\Monitoring;

use DateTimeImmutable;
use DateTimeInterface;

use function in_array;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

/**
 * Health check endpoint for monitoring and load balancers.
 *
 * Returns aggregated health status of all critical dependencies.
 * Used by Grafana and Prometheus for uptime monitoring.
 *
 * @see Story 1.8 - T7: Health Check Endpoint (AC: #2)
 */
#[Route('/health', name: 'health_check', methods: ['GET'])]
final readonly class HealthCheckController
{
    public function __construct(
        private InfrastructureHealthCheckerInterface $healthChecker,
    ) {
    }

    public function __invoke(): JsonResponse
    {
        $checks = $this->healthChecker->checkAll();

        $healthy = !in_array(false, $checks, true);
        $status = $healthy ? 'healthy' : 'unhealthy';
        $httpStatus = $healthy ? Response::HTTP_OK : Response::HTTP_SERVICE_UNAVAILABLE;

        return new JsonResponse([
            'status' => $status,
            'checks' => $checks,
            'timestamp' => (new DateTimeImmutable())->format(DateTimeInterface::RFC3339_EXTENDED),
        ], $httpStatus);
    }
}
