<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mime\MimeTypes;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;

class AngularController extends AbstractController
{
    public function index(string $path = null): Response
    {
        $projectDir = $this->getParameter('kernel.project_dir');
        $basePath = $projectDir . '/public/client/';
        $filePath = $basePath . ($path ?? '');

        // Sicherstellen, dass wir im erlaubten Verzeichnis bleiben
        if (!str_starts_with(realpath($filePath), realpath($basePath))) {
            //throw new NotFoundHttpException('Invalid path');
            $filePath = $basePath . 'index.html';
        }

        if (is_dir($filePath)) {
            $filePath = rtrim($filePath, '/') . '/index.html';
        }

        if (!file_exists($filePath) || is_dir($filePath)) {
            $filePath = $basePath . 'index.html';
        }

        if (!is_readable($filePath)) {
            throw new NotFoundHttpException('File not found or not readable');
        }

        $content = file_get_contents($filePath);
        $mimeTypes = new MimeTypes();
        $mimeType = $mimeTypes->guessMimeType($filePath) ?? 'application/octet-stream';

        $response = new Response($content, Response::HTTP_OK, ['Content-Type' => $mimeType]);
        $response->headers->set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0');

        return $response;
    }
}