<?php

namespace App\Security;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Twig\Environment;

class MaintenanceListener
{
    private $twig;
    private $projectDir;
    private $ipsWhiteList;

    public function __construct(Environment $twig, string $projectDir)
    {
        $this->twig = $twig;
        $this->projectDir = $projectDir;
    }

    public function onKernelRequest(RequestEvent $event)
    {
        if (!$event->isMainRequest()) {
            return;
        }
        $request = $event->getRequest();
        $uri = $request->getRequestUri();
        if (str_contains($uri, '/sentry-tunnel')) {
            return;
        }
        // On vérifie si le fichier existe dans var/.maintenance
        $maintenanceFile = $this->projectDir . '/var/.maintenance';

        if (!file_exists($maintenanceFile)) {
            return;
        }

        $content = $this->twig->render('security/maintenance.twig');
        $event->setResponse(new Response($content, 503));
    }
}
