"""Tenant (client) isolation helpers.

The CRM serves many clients out of one database. Client-portal users must only
ever see their own client's rows. Before this module that was enforced only by
the frontend passing ``?client=<id>`` — a filter the caller could simply omit,
which exposed every client's data (including mailbox and database passwords).

Rules applied here:
  * Internal staff (superuser/staff, or an internal role) see everything.
  * Everyone else — client-portal users AND accounts with no role at all — are
    hard-scoped to their own client.
  * A non-internal user with no client sees nothing (fail closed), rather than
    everything.

Use ``scope_to_client`` inside a ViewSet's ``get_queryset``.
"""

# Roles belonging to the service provider, not to a client.
INTERNAL_ROLES = {
    'system_admin', 'operations_manager', 'team_leader', 'qa_analyst', 'agent',
}


def is_internal(user):
    """True if the user is service-provider staff (sees all clients)."""
    if not user or not getattr(user, 'is_authenticated', False):
        return False
    if user.is_superuser or user.is_staff:
        return True
    role = getattr(getattr(user, 'role', None), 'name', None)
    return role in INTERNAL_ROLES


def is_ticket_readonly(user):
    """True if this user may read tickets but must not change them.

    The System Administrator oversees the platform rather than working the
    queue: they can open any ticket to audit it, but replies, notes, status
    changes and assignment are blocked so an oversight account can never email
    a customer or quietly alter an agent's ticket. Enforced server-side — the
    UI hiding the buttons is a convenience, not the control.
    """
    if not user or not getattr(user, 'is_authenticated', False):
        return False
    return getattr(getattr(user, 'role', None), 'name', None) == 'system_admin'


def scope_to_client(qs, user, lookup='client_id', allow_global=False):
    """Restrict ``qs`` to the rows belonging to ``user``'s client.

    lookup       ORM path from the model to the client id, e.g. 'client_id'
                 or 'ticket__client_id'.
    allow_global When the client FK is nullable and NULL means "shared by every
                 client" (knowledge articles, reply templates), those rows stay
                 visible alongside the user's own.
    """
    if is_internal(user):
        return qs

    client_id = getattr(user, 'client_id', None)
    if not client_id:
        return qs.none()

    if allow_global:
        from django.db.models import Q
        null_lookup = lookup[:-3] + '__isnull' if lookup.endswith('_id') else lookup + '__isnull'
        return qs.filter(Q(**{lookup: client_id}) | Q(**{null_lookup: True}))

    return qs.filter(**{lookup: client_id})
