import { BRANCH_ALLOWED_NAV_KEYS, type NavItemKey } from "@/lib/sidebar-nav";
import { NAV_REQUIRED_PERMISSION } from "@/lib/permissions";

/** Cafe owner (HQ) — billing, taxes, branches. */
export function isCafeOwner(role: string | undefined): boolean {
  return role === "Owner";
}

/** Logged in as a branch-scoped employee (JWT branchId). */
export function isBranchAccount(branchId: string | null | undefined): boolean {
  return !!branchId;
}

// Billing stays a hard owner gate (also covers legacy sessions with no
// permission list). Taxes & branches are now permission-driven via
// NAV_REQUIRED_PERMISSION (ViewTaxes / ViewBranches), which managers hold.
export const OWNER_ONLY_NAV_KEYS = ["subscription"] as const;

export function canSeeNavItem(
  key: string,
  role: string | undefined,
  branchId: string | null | undefined,
  permissions?: Set<string> | null
): boolean {
  // Branch-scoped staff only see daily-operations destinations.
  if (isBranchAccount(branchId) && !BRANCH_ALLOWED_NAV_KEYS.has(key as NavItemKey)) {
    return false;
  }
  if ((OWNER_ONLY_NAV_KEYS as readonly string[]).includes(key) && !isCafeOwner(role)) {
    return false;
  }
  // Permission-based page visibility. `permissions === null` means a legacy
  // session with no permission list — fall back to the role/branch rules above
  // so those users keep their current access until the next token refresh.
  if (permissions) {
    const required = NAV_REQUIRED_PERMISSION[key as NavItemKey];
    if (required && !permissions.has(required)) {
      return false;
    }
  }
  return true;
}
