<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class SecurityHeaders
{
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);
        $entornoLocal = app()->environment(['local', 'development']);
        $sesionAutenticada = (bool) $request->session()->get('cliente_auth', false)
            || (bool) $request->session()->get('personal_auth', false);

        $styleSrc = $entornoLocal
            ? "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net http:;"
            : "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net;";

        $scriptSrc = $entornoLocal
            ? "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net http:;"
            : "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net;";

        $connectSrc = $entornoLocal
            ? "connect-src 'self' http: https: ws: wss:;"
            : "connect-src 'self';";

        $response->headers->set('X-Frame-Options', 'SAMEORIGIN');
        $response->headers->set('X-Content-Type-Options', 'nosniff');
        $response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
        $response->headers->set('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
        $response->headers->set(
            'Content-Security-Policy',
            "default-src 'self'; base-uri 'self'; frame-ancestors 'self'; form-action 'self'; img-src 'self' data: https:; {$styleSrc} {$scriptSrc} font-src 'self' data: https:; {$connectSrc} frame-src 'self' https://maps.google.com https://www.google.com;"
        );

        if ($request->isSecure()) {
            $response->headers->set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
        }

        if ($sesionAutenticada) {
            $response->headers->set('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0, private');
            $response->headers->set('Pragma', 'no-cache');
            $response->headers->set('Expires', 'Thu, 01 Jan 1970 00:00:00 GMT');
        }

        return $response;
    }
}
