import type { ReactNode } from "react";

import { customerPageAllows } from "@/app/customer/_lib/customer-page-guard";
import type { CustomerRouteKey } from "@/config/customer-route-keys";
import { AccessDeniedView } from "@/app/customer/_components/access-denied-view";

type ReportPageGuardProps = {
  tenant: string;
  /** Route key, or several when any one of them grants access. */
  routeKeys: CustomerRouteKey | CustomerRouteKey[];
  /** Report name as the reader knows it, e.g. "Liquidity Report". */
  label: string;
  children: ReactNode;
};

/**
 * Page-level permission gate for customer reports.
 *
 * The BFF data routes are already authorized by `createReportAuthorize` — this is the
 * matching check for the page itself, so an unpermitted reader gets a clear "you don't have
 * access" screen instead of a rendered report shell that then fails its own fetch with a 403
 * (which used to leak an empty/broken content area with just an inline error buried in it).
 *
 * Sits inside each page's own `CustomerPageShell` rather than wrapping it, so pages
 * keep their layout props, Suspense boundaries, and dynamic imports untouched.
 *
 * Reports deny with a named "access denied" view rather than a 404 because the reader knows
 * the report exists — it was in their navigation, or they had it bookmarked before access was
 * revoked — and "You don't have access to the Liquidity Report" is more useful to them than a
 * missing page. Pages where the section's existence is itself privileged should call
 * `requireCustomerPageAccess` instead.
 *
 * The decision — including the convention that an unresolved session is not denied here —
 * now lives in `customerPageAllows`, shared with every other portal page guard.
 */
export async function ReportPageGuard({ tenant, routeKeys, label, children }: ReportPageGuardProps) {
  const keys = Array.isArray(routeKeys) ? routeKeys : [routeKeys];

  if (!(await customerPageAllows(tenant, keys))) {
    return <AccessDeniedView label={label} />;
  }

  return <>{children}</>;
}
