from __future__ import annotations

from fastapi import HTTPException, status

from app.api.deps import CurrentUserContext
from app.services.expense_claim_access_policy import ExpenseClaimAccessPolicy

FINANCE_DASHBOARD_READ_ROLE_CODES = frozenset({"finance", "executive"})


class FinanceDashboardAccessPolicy:
    """财务看板只提供租户内的财务只读视图。"""

    @staticmethod
    def can_read(current_user: CurrentUserContext) -> bool:
        # 租户上下文异常时必须拒绝，不能把空值隐式解释成 default 租户。
        if not str(current_user.tenant_id or "").strip():
            return False
        if current_user.is_admin:
            return True
        role_codes = ExpenseClaimAccessPolicy.normalize_role_codes(current_user)
        return bool(role_codes & FINANCE_DASHBOARD_READ_ROLE_CODES)

    @classmethod
    def require_read(cls, current_user: CurrentUserContext) -> None:
        if cls.can_read(current_user):
            return
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有财务人员、高级财务人员或 admin 管理员可以查看财务看板。",
        )
