namespace Atomx.Admin.Middlewares
{
    /// <summary>
    /// 安全中间件
    /// </summary>
    public class SecurityHeadersMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IWebHostEnvironment _environment;

        public SecurityHeadersMiddleware(RequestDelegate next, IWebHostEnvironment environment)
        {
            _next = next;
            _environment = environment;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            // 添加安全头
            if (!context.Response.HasStarted)
            {
                var headers = context.Response.Headers;

                // CSP策略
                if (!_environment.IsDevelopment())
                {
                    headers.Append("Content-Security-Policy",
                        "default-src 'self'; " +
                        "script-src 'self' 'unsafe-inline' 'unsafe-eval'; " +
                        "style-src 'self' 'unsafe-inline'; " +
                        "img-src 'self' data: https:; " +
                        "font-src 'self'; " +
                        "connect-src 'self' wss:; " +
                        "frame-ancestors 'none';");
                }

                // 其他安全头
                headers.Append("X-Content-Type-Options", "nosniff");
                headers.Append("X-Frame-Options", "DENY");
                headers.Append("X-XSS-Protection", "1; mode=block");
                headers.Append("Referrer-Policy", "strict-origin-when-cross-origin");
                headers.Append("Permissions-Policy",
                    "camera=(), microphone=(), geolocation=(), interest-cohort=()");

                // HSTS（在生产环境中启用）
                if (!_environment.IsDevelopment())
                {
                    headers.Append("Strict-Transport-Security",
                        "max-age=31536000; includeSubDomains; preload");
                }
            }

            await _next(context);
        }
    }
}
