/**
 * Who may do what in the portal. The API is the real gate (every route checks
 * the role); this mirrors it so people only see what they can use.
 *
 * The roles and their permissions come from the server at sign-in
 * (`user.permissions`), so a change on the server needs no change here.
 */
export type Permission =
  | "orders.view"
  | "orders.manage"
  | "menu.view"
  | "menu.manage"
  | "menu.availability"
  | "reviews.view"
  | "analytics.view"
  | "earnings.view"
  | "payouts.manage"
  | "settings.manage"
  | "team.manage";

export type Role = "owner" | "manager" | "kitchen";

export interface PortalUser {
  /** The staff member's id, or null for the owner. */
  id: number | null;
  name: string;
  email: string;
  role: Role;
  role_label: string;
  permissions: Permission[];
}

export function hasPermission(user: PortalUser | null | undefined, permission: Permission): boolean {
  return !!user && user.permissions.includes(permission);
}

/**
 * The permission each page needs. A page not listed is open to every
 * signed-in person. Longest path wins, so `/orders/history` is checked on
 * its own and not as `/orders`.
 */
const PAGE_PERMISSIONS: [prefix: string, permission: Permission][] = [
  ["/orders/history", "orders.view"],
  ["/orders", "orders.view"],
  ["/dashboard", "orders.view"],
  ["/menu", "menu.view"],
  ["/reviews", "reviews.view"],
  ["/analytics", "analytics.view"],
  ["/earnings", "earnings.view"],
  ["/payouts", "payouts.manage"],
  ["/team", "team.manage"],
  ["/settings", "settings.manage"],
];

export function permissionForPath(pathname: string): Permission | null {
  const match = [...PAGE_PERMISSIONS]
    .sort((a, b) => b[0].length - a[0].length)
    .find(([prefix]) => pathname === prefix || pathname.startsWith(prefix + "/"));
  return match ? match[1] : null;
}

export function canVisit(user: PortalUser | null | undefined, pathname: string): boolean {
  const needed = permissionForPath(pathname);
  return needed === null || hasPermission(user, needed);
}

/** Where a person lands after signing in, and where they are sent from a page they can't open. */
export function homeFor(user: PortalUser | null | undefined): string {
  // Someone who runs the kitchen, not the books, lands on the order board.
  if (!hasPermission(user, "earnings.view") && canVisit(user, "/orders")) return "/orders";

  const order = ["/dashboard", "/orders", "/menu", "/reviews"];
  return order.find((path) => canVisit(user, path)) ?? "/settings/profile";
}

/**
 * Someone who signed in before roles existed has no stored user. They were the
 * owner, and the API still checks every call, so treat them as the owner until
 * the portal refreshes its copy from the server.
 */
export const OWNER_PERMISSIONS: Permission[] = [
  "orders.view", "orders.manage", "menu.view", "menu.manage", "menu.availability", "reviews.view",
  "analytics.view", "earnings.view", "payouts.manage", "settings.manage", "team.manage",
];
