from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import Response
from ..config.logging_config import get_logger
from ..config.settings import settings
logger = get_logger(__name__)

class SecurityHeadersMiddleware(BaseHTTPMiddleware):

    async def dispatch(self, request: Request, call_next):
        response = await call_next(request)
        security_headers = {'X-Content-Type-Options': 'nosniff', 'X-Frame-Options': 'DENY', 'X-XSS-Protection': '1; mode=block', 'Referrer-Policy': 'strict-origin-when-cross-origin', 'Permissions-Policy': 'geolocation=(), microphone=(), camera=()'}
        security_headers.setdefault('Cross-Origin-Resource-Policy', 'cross-origin')
        if settings.is_production:
            security_headers['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' data:; connect-src 'self'"
        if settings.is_production:
            security_headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
        for header, value in security_headers.items():
            response.headers[header] = value
        return response