from __future__ import annotations

from sqlalchemy import select
from sqlalchemy.orm import Session

from app.modules.core.iam.scope import (
    UserScope,
    list_visible_branches,
    list_visible_tenants,
)
from app.modules.core.tenancy.models import Branch
from app.modules.core.iam.services import paginate_list


def build_tenants_payload(
    db: Session,
    scope: UserScope,
    q: str | None = None,
    page: int = 1,
    per_page: int = 10,
) -> dict:
    tenants = list_visible_tenants(db, scope)
    query = (q or "").strip().lower()

    if query:
        tenants = [
            t
            for t in tenants
            if query in (t.name or "").lower()
            or query in (t.code or "").lower()
        ]

    paged = paginate_list(tenants, page=page, per_page=per_page)

    return {
        "tenants": paged.items,
        "tenants_page": paged,
        "filters": {
            "q": (q or "").strip(),
            "per_page": paged.per_page,
        },
    }


def build_branches_payload(
    db: Session,
    scope: UserScope,
    q: str | None = None,
    tenant_id: int | None = None,
    page: int = 1,
    per_page: int = 10,
) -> dict:
    if scope.is_system_admin:
        effective_tenant_id = tenant_id

        if effective_tenant_id is None:
            branches = db.execute(
                select(Branch).order_by(Branch.name)
            ).scalars().all()
        else:
            branches = db.execute(
                select(Branch)
                .where(Branch.tenant_id == effective_tenant_id)
                .order_by(Branch.name)
            ).scalars().all()
    else:
        effective_tenant_id = scope.actor.tenant_id
        branches = list_visible_branches(db, scope, effective_tenant_id)

    query = (q or "").strip().lower()
    if query:
        branches = [
            b
            for b in branches
            if query in (b.name or "").lower()
            or query in (b.code or "").lower()
            or query in (b.timezone or "").lower()
        ]

    paged = paginate_list(branches, page=page, per_page=per_page)
    tenants = {t.id: t for t in list_visible_tenants(db, scope)}

    return {
        "branches": paged.items,
        "branches_page": paged,
        "tenants": tenants,
        "filters": {
            "q": (q or "").strip(),
            "per_page": paged.per_page,
            "tenant_id": effective_tenant_id,
        },
    }