<?php

declare(strict_types=1);

namespace App\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Psr7\Response;

class MaintenanceMiddleware
{
    public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $maintenance = $_ENV['MAINTENANCE_MODE'] ?? 'false';

        if ($maintenance === 'true') {
            // Laisser passer le health check
            $path = $request->getUri()->getPath();
            if ($path === '/api/health') {
                return $handler->handle($request);
            }

            $response = new Response();
            $response->getBody()->write(json_encode([
                'error'   => true,
                'code'    => 'MAINTENANCE',
                'message' => 'Maintenance en cours — réessayez dans quelques minutes'
            ]));
            return $response->withHeader('Content-Type', 'application/json')->withStatus(503);
        }

        return $handler->handle($request);
    }
}
