<?php

namespace App\Http\Middleware;

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

class ResponseSecurityHeaders
{
    public function handle(Request $request, Closure $next): Response
    {
        /** @var Response $response */
        $response = $next($request);

        $permissionsPolicy = $request->is('event', 'e/*', 'g/*', 'share/*')
            ? 'camera=(self), microphone=(), geolocation=()'
            : 'camera=(), microphone=(), geolocation=()';

        $headers = [
            'Referrer-Policy' => 'strict-origin-when-cross-origin',
            'X-Content-Type-Options' => 'nosniff',
            'X-Frame-Options' => 'SAMEORIGIN',
            'Permissions-Policy' => $permissionsPolicy,
        ];

        foreach ($headers as $name => $value) {
            if (! $response->headers->has($name)) {
                $response->headers->set($name, $value);
            }
        }

        $forceHsts = (bool) config('security_headers.force_hsts', false);

        if ($forceHsts || ($request->isSecure() && ! app()->environment(['local', 'testing']))) {
            $hsts = 'max-age=31536000; includeSubDomains';
            if (! $response->headers->has('Strict-Transport-Security')) {
                $response->headers->set('Strict-Transport-Security', $hsts);
            }
        }

        return $response;
    }
}
