"""Helpers de portée multi-agences : échec fermé par défaut."""
from __future__ import annotations


class ScopeError(PermissionError):
    pass


def allowed_agencies(user):
    """Retourne le queryset des agences visibles par l'utilisateur."""
    from apps.agencies.models import Agency

    if not getattr(user, "is_authenticated", False):
        return Agency.objects.none()
    if user.is_national_admin:
        return Agency.objects.all()
    ids = user.agency_ids()
    return Agency.objects.filter(id__in=ids)


def allowed_agency_ids(user) -> list:
    return list(allowed_agencies(user).values_list("id", flat=True))


def resolve_agency(user, agency_id):
    """Retourne l'agence demandée si elle est dans le périmètre, sinon None."""
    if not agency_id:
        return None
    from apps.agencies.models import Agency

    qs = allowed_agencies(user).filter(id=agency_id)
    return qs.first()


def require_agency(user, agency_id):
    agency = resolve_agency(user, agency_id)
    if agency is None:
        raise ScopeError("Agence hors périmètre")
    return agency
