"""Read-only query selectors for the accounts app."""

from __future__ import annotations

from django.contrib.auth import get_user_model
from django.db.models import QuerySet

User = get_user_model()

__all__ = [
    "get_user_by_id",
    "get_user_by_mobile",
    "get_user_by_email",
    "list_users_for_tenant",
]


def get_user_by_id(user_id: int) -> User:
    """Return the User with the given PK.

    Raises ``User.DoesNotExist`` when not found.
    """
    return User.objects.get(pk=user_id)


def get_user_by_mobile(mobile: str) -> User | None:
    """Return the active User with this mobile number, or ``None``."""
    return User.objects.filter(mobile=mobile, is_active=True).first()


def get_user_by_email(email: str) -> User | None:
    """Return the active User with this email address, or ``None``."""
    return User.objects.filter(email__iexact=email, is_active=True).first()


def list_users_for_tenant(tenant_id: int) -> QuerySet:
    """Return all active Users that have at least one Membership in this tenant.

    Joins through ``memberships.Membership`` so no direct tenant FK on User is
    required.  The QuerySet is distinct to avoid duplicate rows from multiple
    memberships.
    """
    from simorgh.apps.memberships.models import Membership, MembershipStatus

    user_ids = (
        Membership.objects.filter(tenant_id=tenant_id, status=MembershipStatus.ACTIVE)
        .values_list("users", flat=True)
        .distinct()
    )
    return User.objects.filter(pk__in=user_ids, is_active=True).order_by("mobile")
