namespace SolutionErp.Api.Middleware;

// Thêm security headers theo OWASP + Mozilla Observatory best practices.
// Xem docs/guides/security-checklist.md §A05.
public class SecurityHeadersMiddleware(RequestDelegate next)
{
    public async Task InvokeAsync(HttpContext context)
    {
        var headers = context.Response.Headers;

        // Ẩn server fingerprint
        headers.Remove("Server");
        headers.Remove("X-Powered-By");
        headers.Remove("X-AspNet-Version");
        headers.Remove("X-AspNetMvc-Version");

        // Security headers
        headers["X-Content-Type-Options"] = "nosniff";
        headers["X-Frame-Options"] = "DENY";
        headers["Referrer-Policy"] = "strict-origin-when-cross-origin";
        headers["X-Permitted-Cross-Domain-Policies"] = "none";
        headers["Permissions-Policy"] = "geolocation=(), microphone=(), camera=(), payment=()";

        // CSP chỉ áp dụng ở non-Swagger (Swagger dùng inline script/style)
        var isSwagger = context.Request.Path.StartsWithSegments("/swagger");
        if (!isSwagger)
        {
            headers["Content-Security-Policy"] =
                "default-src 'self'; " +
                "img-src 'self' data:; " +
                "style-src 'self' 'unsafe-inline'; " +  // Tailwind cần inline styles ở runtime
                "script-src 'self'; " +
                "font-src 'self' data:; " +
                "connect-src 'self'; " +
                "frame-ancestors 'none'; " +
                "base-uri 'self'; " +
                "form-action 'self'";
        }

        await next(context);
    }
}
