<?php

namespace App\EventListener;

use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;

/**
 * Intercepte toutes les requêtes HTTP.
 * Si maintenance.flag existe → affiche la page de maintenance.
 * Les routes /admin/sync/** et les assets sont exemptés.
 */
#[AsEventListener(event: KernelEvents::REQUEST, priority: 100)]
class MaintenanceListener
{
    public function __construct(
        private string      $projectDir,
        private Environment $twig,
    ) {}

    public function __invoke(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $flagPath = $this->projectDir . '/public/maintenance.flag';

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

        $request    = $event->getRequest();
        $pathInfo   = $request->getPathInfo();

        // Laisser passer : routes admin sync + assets statiques
        $allowedPrefixes = [
            '/admin/sync',
            '/_wdt',   // Symfony profiler
            '/_profiler',
            '/bundles',
        ];

        foreach ($allowedPrefixes as $prefix) {
            if (str_starts_with($pathInfo, $prefix)) {
                return;
            }
        }

        // Extensions statiques : on laisse passer
        $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
        if (in_array($ext, ['css', 'js', 'png', 'jpg', 'ico', 'woff', 'woff2', 'svg'], true)) {
            return;
        }

        // Afficher la page de maintenance
        $html = $this->twig->render('maintenance/index.html.twig', [
            'since' => file_get_contents($flagPath),
        ]);

        $event->setResponse(new Response($html, Response::HTTP_SERVICE_UNAVAILABLE));
    }
}
