import {
  ADMIN_PERMISSIONS,
  ADMIN_ROLE,
  type Permission,
} from "@/lib/constants/auth";
import { forbidden } from "@/modules/auth/errors";

export type AuthContext =
  | { type: "admin"; userId: string; role: typeof ADMIN_ROLE }
  | {
      type: "service";
      customerId: string;
      permissions: Permission[];
    };

/** RBAC 权限检查，无权限抛 FORBIDDEN */
export function requirePermission(
  auth: AuthContext,
  permission: Permission,
): void {
  if (auth.type === "admin") {
    if (ADMIN_PERMISSIONS.includes(permission)) {
      return;
    }
    throw forbidden(`缺少权限: ${permission}`);
  }

  if (auth.permissions.includes(permission)) {
    return;
  }
  throw forbidden(`缺少权限: ${permission}`);
}
