from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import select

from app.core.db.deps import get_common_db
from app.core.security.session_auth import require_login
from app.modules.core.iam.models import User
from app.modules.core.rbac.deps import get_user_roles
from app.modules.core.tenancy.models import Tenant, Branch

router = APIRouter(prefix="/tenancy", tags=["tenancy"])


def _require_tenancy_api_access(db: Session, user: User) -> None:
    roles = set(get_user_roles(db, int(user.id)))
    if not roles.intersection({"System Admin", "Firm Admin"}):
        raise HTTPException(status_code=403, detail="Tenancy API access denied")


def _tenant_payload(t: Tenant) -> dict:
    return {
        "id": t.id,
        "code": getattr(t, "code", None),
        "name": getattr(t, "name", None),
        "is_active": getattr(t, "is_active", None),
    }


def _branch_payload(b: Branch) -> dict:
    return {
        "id": b.id,
        "tenant_id": getattr(b, "tenant_id", None),
        "code": getattr(b, "code", None),
        "name": getattr(b, "name", None),
        "is_active": getattr(b, "is_active", None),
    }


@router.get("/tenants")
def list_tenants(db: Session = Depends(get_common_db), current_user: User = Depends(require_login)):
    _require_tenancy_api_access(db, current_user)
    stmt = select(Tenant).order_by(Tenant.id)
    roles = set(get_user_roles(db, int(current_user.id)))
    if "System Admin" not in roles:
        stmt = stmt.where(Tenant.id == current_user.tenant_id)
    return [_tenant_payload(t) for t in db.execute(stmt).scalars().all()]


@router.get("/branches")
def list_branches(db: Session = Depends(get_common_db), current_user: User = Depends(require_login)):
    _require_tenancy_api_access(db, current_user)
    stmt = select(Branch).order_by(Branch.id)
    roles = set(get_user_roles(db, int(current_user.id)))
    if "System Admin" not in roles:
        stmt = stmt.where(Branch.tenant_id == current_user.tenant_id)
    return [_branch_payload(b) for b in db.execute(stmt).scalars().all()]
