import type { ReactNode } from "react";

import type { CustomerRouteKey } from "@/config/customer-route-keys";
import { ErrorBanner } from "@/components/shared/error-banner";
import { getCustomerSessionContext } from "@/lib/frontend-auth/server";

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 message
 * instead of a rendered report shell that then fails its own fetch with a 403.
 *
 * Sits inside each page's own `CustomerPageShell` rather than wrapping it, so pages
 * keep their layout props, Suspense boundaries, and dynamic imports untouched.
 *
 * Matches the pre-existing convention: the gate only applies to a resolved session.
 * When `session.user` is null the reader is unauthenticated and the surrounding auth
 * flow — not this guard — decides what happens.
 */
export async function ReportPageGuard({ tenant, routeKeys, label, children }: ReportPageGuardProps) {
  const keys = Array.isArray(routeKeys) ? routeKeys : [routeKeys];
  const session = await getCustomerSessionContext(tenant);
  const denied =
    session.user != null && !keys.some((routeKey) => session.permissions.routes.includes(routeKey));

  if (denied) {
    return <ErrorBanner message={`Permission denied for the ${label}.`} />;
  }

  return <>{children}</>;
}
