"""Branch sales monitoring — HQ network view vs single-branch scope."""
from __future__ import annotations

from typing import Any, Dict, Optional, Tuple

from fastapi import HTTPException
from sqlalchemy.orm import Session

from app.models.branch import Branch
from app.models.user import User

# Roles that may view all branches when logged in at HQ (or any branch for super_admin)
NETWORK_VIEW_ROLES = frozenset({"super_admin", "admin", "accountant", "manager"})


def resolve_monitoring_scope(db: Session, user: User) -> Dict[str, Any]:
    """
    HQ / admin users monitor all branches in their company.
    Other users see only their assigned branch.
    """
    company_id = getattr(user, "company_id", None)
    user_branch: Optional[Branch] = None

    if user.branch_id:
        user_branch = db.query(Branch).filter(Branch.id == user.branch_id).first()
        if user_branch and not company_id:
            company_id = user_branch.company_id

    role = (getattr(user, "role", None) or "").lower()
    is_hq = bool(user_branch and user_branch.is_head_office)
    view_all = is_hq or role in NETWORK_VIEW_ROLES

    return {
        "company_id": company_id,
        "view_all_branches": view_all,
        "branch_id": None if view_all else user.branch_id,
        "is_head_office": is_hq,
        "monitoring_mode": "network" if view_all else "branch",
        "user_branch_name": user_branch.name if user_branch else None,
    }


def assert_branch_visible(db: Session, scope: Dict[str, Any], branch_id: str) -> Branch:
    branch = db.query(Branch).filter(Branch.id == branch_id).first()
    if not branch:
        raise HTTPException(status_code=404, detail="Branch not found")

    if scope.get("company_id") and branch.company_id and branch.company_id != scope["company_id"]:
        raise HTTPException(status_code=403, detail="Branch not in your company")

    if not scope.get("view_all_branches") and scope.get("branch_id") != branch_id:
        raise HTTPException(
            status_code=403,
            detail="Head office or administrator access required to view other branches",
        )
    return branch


def sale_timestamp_sql(alias: str = "s") -> str:
    """Effective sale timestamp column expression (POS uses date; fallback created_at)."""
    return f"COALESCE({alias}.date, {alias}.created_at)"
