<?php

namespace AleshaCMS\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);

        $response->headers->set('X-Generator', 'AleshaCMS');
        $response->headers->set('X-Content-Type-Options', 'nosniff');
        $response->headers->set('X-Frame-Options', 'SAMEORIGIN');
        $response->headers->set('X-XSS-Protection', '1; mode=block');
        $response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');

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

        $response->headers->set('Cross-Origin-Opener-Policy', 'same-origin-allow-popups');
        $response->headers->set('Cross-Origin-Resource-Policy', 'same-site');

        $response->headers->set('Permissions-Policy', implode(', ', [
            'geolocation=()',
            'camera=()',
            'microphone=()',
            'payment=()',
            'usb=()',
            'fullscreen=(self)',
            'interest-cohort=()',
        ]));

        if (! app()->environment('local', 'testing')) {
            $response->headers->set('Content-Security-Policy', $this->buildCsp());
        }

        return $response;
    }

    private function buildCsp(): string
    {
        $disqusShortname = \AleshaCMS\Models\CMS\Setting::get('disqus_shortname', '');
        $disqusActive    = \AleshaCMS\Models\CMS\Plugin::where('slug', 'Disqus')->where('is_active', true)->exists();

        $scriptSrc = [
            "'self'",
            "'unsafe-inline'",
            'https://cdn.jsdelivr.net',      // Alpine.js CDN
        ];

        $frameSrc = ["'self'"];
        $connectSrc = ["'self'"];

        if ($disqusActive && $disqusShortname) {
            $scriptSrc[]  = "https://{$disqusShortname}.disqus.com";
            $scriptSrc[]  = 'https://disqus.com';
            $scriptSrc[]  = 'https://c.disquscdn.com';
            $frameSrc[]   = 'https://disqus.com';
            $connectSrc[] = "https://{$disqusShortname}.disqus.com";
            $connectSrc[] = 'https://disqus.com';
        }

        $directives = [
            "default-src 'self'",
            "script-src " . implode(' ', $scriptSrc),
            "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
            "font-src 'self' data: https://fonts.gstatic.com",
            "img-src 'self' data: blob: https:",
            "media-src 'self'",
            "connect-src " . implode(' ', $connectSrc),
            "frame-src " . implode(' ', $frameSrc),
            "object-src 'none'",
            "base-uri 'self'",
            "form-action 'self'",
            "upgrade-insecure-requests",
        ];

        return implode('; ', $directives);
    }
}
