export const metadata = { title: "Customers" };
import { DashboardPage } from "@/components/layout/dashboard-page";
import { PageHeader, PreviewNotice } from "@/components/shared/page";
import { getDashboardRole } from "@/lib/auth/dashboard-role";
import { isMonetizationApiConfigured } from "@/lib/auth/server-config";
import { canManage } from "@/lib/preview";
import {
  CustomerApiError,
  getCustomers,
} from "@/features/people/api";
import { CustomerView } from "@/features/people/customer-view";
import { readCustomerListQuery } from "@/features/people/customer-query";

export default async function DashboardRoute(props: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const searchParams = await props.searchParams;
  const role = await getDashboardRole(
    Array.isArray(searchParams.role) ? searchParams.role[0] : searchParams.role,
  );
  const query = readCustomerListQuery(searchParams);
  const apiConfigured = isMonetizationApiConfigured();
  const previewState = Array.isArray(searchParams.state)
    ? searchParams.state[0]
    : searchParams.state;
  if (!apiConfigured && !canManage(role)) {
    return (
      <DashboardPage role={role}>
        <PageHeader title="Customers" />
        <PreviewNotice>This preview identity cannot manage customers.</PreviewNotice>
      </DashboardPage>
    );
  }
  let page = null;
  let error = "";
  if (!apiConfigured && previewState === "error") {
    error = "Customer data is unavailable in this preview state.";
  } else if (apiConfigured) {
    try {
      page = await getCustomers(query);
    } catch (cause) {
      error = cause instanceof CustomerApiError
        ? cause.message
        : "The customer service is unavailable. Please try again.";
    }
  }
  return (
    <DashboardPage role={role}>
      <CustomerView
        query={query}
        page={page}
        apiConfigured={apiConfigured}
        error={error}
        previewEmpty={!apiConfigured && previewState === "empty"}
      />
    </DashboardPage>
  );
}
