<?php

declare(strict_types=1);

namespace App\Controllers;

use App\ApiClient\ApiHealth;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

/**
 * UI healthcheck. Always 200 unless the UI itself is broken — the api's
 * reachability is reported in the body so an api-down event doesn't
 * cause the orchestrator to kill the UI (which would then show the
 * user nothing instead of a degraded page).
 */
final class HealthzController
{
    public function __construct(private readonly ApiHealth $health)
    {
    }

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $payload = [
            'status' => 'ok',
            'api_reachable' => $this->health->isReachable(),
            'last_api_check_at' => $this->health->lastSuccessAt()?->format('Y-m-d\TH:i:s\Z'),
        ];
        $response->getBody()->write((string) json_encode($payload));

        return $response->withHeader('Content-Type', 'application/json');
    }
}
