<?php

declare(strict_types=1);

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[IsGranted('ROLE_USER')]
class SpaController extends AbstractController
{
    public function __construct(
        #[Autowire('%kernel.project_dir%/public/build')]
        private readonly string $buildDir,
    ) {}

    #[Route(
        '/{path}',
        name: 'spa',
        requirements: ['path' => '^(?!api|setup|token|login|register|logout|_profiler|_wdt).*'],
        defaults: ['path' => ''],
    )]
    public function index(): Response
    {
        $indexFile = $this->buildDir . '/index.html';

        if (!file_exists($indexFile)) {
            throw $this->createNotFoundException('SPA not built — run npm run build in frontend/.');
        }

        return new Response(
            content: (string) file_get_contents($indexFile),
            headers: ['Content-Type' => 'text/html; charset=utf-8'],
        );
    }
}
