import { useAuthStore } from "@/lib/stores/auth.store";
import type { NavItemKey } from "@/lib/sidebar-nav";

/**
 * Client mirror of the backend `Meezi.Core.Authorization.Permission` enum. The
 * server (EnsurePermission) remains the single source of truth — these values
 * only drive what the UI *shows* (pages, action buttons). Never rely on them
 * for actual security.
 */
export type Permission =
  | "ManageCafeSettings"
  | "ManageBilling"
  | "ManageBranches"
  | "ManageStaff"
  | "ManageMenu"
  | "ManageInventory"
  | "ManageExpenses"
  | "ManageTaxes"
  | "ManageCoupons"
  | "ManageReservations"
  | "ManageTables"
  | "ViewReports"
  | "ReviewLeave"
  | "ManageSalaries"
  | "ManagePrintSettings"
  | "ProcessOrders"
  | "HandlePayments"
  | "OperateRegister"
  | "ManageQueue"
  | "ViewKitchen"
  | "HandleDelivery";

/**
 * Permission a nav page requires to be visible. Pages not listed here fall back
 * to the existing owner-only / branch-account visibility logic in
 * {@link file://./auth-permissions.ts}.
 */
export const NAV_REQUIRED_PERMISSION: Partial<Record<NavItemKey, Permission>> = {
  pos: "ProcessOrders",
  tables: "ManageTables",
  queue: "ManageQueue",
  kds: "ViewKitchen",
  reservations: "ManageReservations",
  menu: "ManageMenu",
  inventory: "ManageInventory",
  coupons: "ManageCoupons",
  reports: "ViewReports",
  expenses: "ManageExpenses",
  shifts: "OperateRegister",
  taxes: "ManageTaxes",
  hr: "ManageStaff",
};

/** Read the effective permission set off an auth response (null = legacy session). */
export function permissionsOf(
  user: { permissions?: string[] | null } | null | undefined
): Set<string> | null {
  if (!user?.permissions) return null;
  return new Set(user.permissions);
}

/**
 * Whether the user holds a capability. Legacy sessions (no permissions array, e.g.
 * issued before this feature shipped) return `true` so the UI degrades gracefully
 * until the next token refresh — the server still enforces real access.
 */
export function hasPermission(
  user: { permissions?: string[] | null } | null | undefined,
  permission: Permission
): boolean {
  const set = permissionsOf(user);
  if (set === null) return true;
  return set.has(permission);
}

/** React hook: does the current user hold the given permission? */
export function useHasPermission(permission: Permission): boolean {
  const user = useAuthStore((s) => s.user);
  return hasPermission(user, permission);
}
