"""Validate HTTP Host against System Admin integration settings (DB-backed)."""
from __future__ import annotations

from django.http import HttpResponseBadRequest

from system_administration.host_policy import get_allowed_hosts


class DbAllowedHostsMiddleware:
    """Reject requests whose Host header is not in the DB-managed allow-list."""

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

    def __call__(self, request):
        host = (request.META.get('HTTP_HOST') or '').split(':')[0].strip().lower()
        if host and host not in get_allowed_hosts():
            return HttpResponseBadRequest('Invalid host header')
        return self.get_response(request)
