from django.db import DatabaseError
from django.http import JsonResponse

from .models import SecurityLoginEvent, SystemConfigurationEntry, SystemMaintenanceState


def _get_client_ip(request) -> str:
    xff = request.META.get("HTTP_X_FORWARDED_FOR")
    if xff:
        return xff.split(",")[0].strip()
    return request.META.get("REMOTE_ADDR") or ""


class MaintenanceAndSessionPolicyMiddleware:
    """Enforces maintenance mode and admin IP allowlist rules cleanly."""

    BYPASS_PREFIXES = (
        "/api/v1/auth/",
        "/api/admin/",
        "/api/v1/admin/",
        "/api/schema/",
        "/api/docs/",
    )

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        path = request.path or ""
        if path.startswith("/api/"):
            client_ip = _get_client_ip(request)
            try:
                if path.startswith(("/api/admin/", "/api/v1/admin/")) and not path.startswith(
                    ("/api/admin/health/", "/api/v1/admin/health/", "/api/admin/maintenance/", "/api/v1/admin/maintenance/")
                ):
                    allow_cfg = SystemConfigurationEntry.objects.filter(
                        scope=SystemConfigurationEntry.Scope.GLOBAL,
                        category=SystemConfigurationEntry.Category.SECURITY,
                        key="admin_ip_allowlist",
                    ).first()
                    allowed_ips = (allow_cfg.value_json or {}).get("ips", []) if allow_cfg else []
                    if allowed_ips and client_ip not in allowed_ips:
                        SecurityLoginEvent.objects.create(
                            user=request.user if getattr(request, "user", None) and request.user.is_authenticated else None,
                            username_attempted=getattr(getattr(request, "user", None), "username", "") or "anonymous",
                            event_type=SecurityLoginEvent.EventType.IP_BLOCKED,
                            ip_address=client_ip or None,
                            failure_reason=f"Blocked admin access from IP {client_ip}",
                        )
                        return JsonResponse(
                            {"detail": f"IP address {client_ip} is not in the admin allowlist."},
                            status=403,
                        )

                if not path.startswith(self.BYPASS_PREFIXES):
                    state = SystemMaintenanceState.objects.order_by("-updated_at").first()
                    if state and state.is_maintenance_mode:
                        user = getattr(request, "user", None) or getattr(request, "_force_auth_user", None)
                        is_super = bool(user and getattr(user, "is_authenticated", False) and getattr(user, "is_superuser", False))
                        if not is_super and client_ip not in (state.allowed_ips or []):
                            return JsonResponse(
                                {
                                    "detail": state.reason or "Maya OS is currently in scheduled maintenance mode.",
                                    "maintenance_mode": True,
                                    "banner_message": state.banner_message,
                                },
                                status=503,
                            )
            except DatabaseError:
                pass

        return self.get_response(request)

