from __future__ import annotations

from typing import Optional

from django.utils.deprecation import MiddlewareMixin
from django.contrib.sites.models import Site

from .models import OrganizationSite, Organization


class CurrentOrganizationMiddleware(MiddlewareMixin):
    def process_request(self, request):
        request.site = None  # type: ignore[attr-defined]
        request.org: Optional[Organization] = None  # type: ignore[attr-defined]

        host = request.get_host().split(":")[0].lower()

        # Resolve Site by host
        try:
            request.site = Site.objects.get(domain__iexact=host)
        except Site.DoesNotExist:
            try:
                request.site = Site.objects.get_current()
            except Exception:
                request.site = None

        # Map Site -> Organization
        if request.site is not None:
            try:
                mapping = OrganizationSite.objects.select_related("organization").get(site=request.site)
                request.org = mapping.organization
            except OrganizationSite.DoesNotExist:
                request.org = None

        # Fallback to user's org if not mapped
        if request.org is None and getattr(request, "user", None) and request.user.is_authenticated:
            request.org = getattr(getattr(request.user, "recycle_profile", None), "organization", None)

        return None

