import { ROUTES } from "@/lib/constants/routes";
import { UserRole } from "@/types/auth";
import type { AccessCheck } from "@/types/rbac";

/**
 * Route-level ("view") access — the SINGLE source of truth for both `proxy.ts`
 * route gating and sidebar visibility. Longest-matching prefix wins.
 *
 * Routes not listed here are open to any authenticated user of the panel: the
 * two dashboards are intentionally ungated — they are the always-reachable
 * landing page and the redirect target when a finer route is denied (which is
 * also why gating them by `dashboard-read` would be wrong — PROVIDER_TECHNICIAN
 * has no `dashboard-read` in the seed).
 *
 * Mapping rule: use the permission where it cleanly matches the intended access;
 * fall back to a role check only where the product is deliberately stricter than
 * the backend `@Roles`/seed can express (noted per line). Verified against the
 * backend controllers so no gate creates a 403 nav item.
 */
export const ROUTE_ACCESS: { prefix: string; access: AccessCheck }[] = [
  // ── Admin ────────────────────────────────────────────────────────────────
  { prefix: ROUTES.ADMIN.PROVIDERS, access: { permission: "provider-read" } },
  { prefix: ROUTES.ADMIN.CATALOG, access: { permission: "catalog-read" } },
  // Backend allows both admins; product shows Customers to Super only.
  { prefix: ROUTES.ADMIN.CUSTOMERS, access: { role: UserRole.ADMIN_SUPER } },
  // ── Provider ─────────────────────────────────────────────────────────────
  { prefix: ROUTES.SUPPLIER.SCHEDULE, access: { permission: "booking-read" } },
  {
    prefix: ROUTES.SUPPLIER.SERVICES,
    access: { permission: "catalog-update" },
  },
  // Backend allows owner+manager; product shows Packages to Owner only.
  {
    prefix: ROUTES.SUPPLIER.PACKAGES,
    access: { role: UserRole.PROVIDER_OWNER },
  },
];

/**
 * Longest-prefix match of a pathname to its required access.
 * Returns null when the route is ungated (open to any authenticated panel user).
 */
export function resolveRouteAccess(pathname: string): AccessCheck | null {
  let best: { prefix: string; access: AccessCheck } | null = null;
  for (const entry of ROUTE_ACCESS) {
    if (pathname === entry.prefix || pathname.startsWith(entry.prefix + "/")) {
      if (!best || entry.prefix.length > best.prefix.length) best = entry;
    }
  }
  return best?.access ?? null;
}
