import { CustomerPageShell } from "@/app/customer/_components/customer-page-shell";
import { CustomerDeepdexPage } from "@/app/customer/[tenant]/deepdex/_components/customer-deepdex-page";
import { DEEPDEX_PERMISSION } from "@/app/customer/[tenant]/deepdex/_lib/deepdex-route";
import { fetchCustomerDeepdexList } from "@/app/customer/[tenant]/deepdex/_lib/deepdex-server-api";
import { deepdexSettingsDefaults } from "@/components/deepdex/data/deepdex-settings.defaults";
import { getCustomerSessionContext } from "@/lib/frontend-auth/server";

type PageProps = {
  params: Promise<{ tenant: string }>;
  searchParams: Promise<{ page?: string; pageSize?: string }>;
};

export default async function CustomerDeepdexRoutePage({ params, searchParams }: PageProps) {
  const { tenant } = await params;
  const query = await searchParams;
  const session = await getCustomerSessionContext(tenant);
  const hasPermission = session.permissions.routes.includes(DEEPDEX_PERMISSION);

  if (!hasPermission) {
    return (
      <CustomerPageShell>
        <CustomerDeepdexPage
          tenant={tenant}
          initialItems={[]}
          initialTotalCount={0}
          initialPage={1}
          initialPageSize={20}
          initialPageCount={0}
          permissionDenied
        />
      </CustomerPageShell>
    );
  }

  const page = Math.max(1, Number(query.page) || 1);
  const pageSize = Math.min(100, Math.max(1, Number(query.pageSize) || 20));
  const result = await fetchCustomerDeepdexList(tenant, { page, pageSize });

  return (
    <CustomerPageShell>
      <CustomerDeepdexPage
        tenant={tenant}
        initialItems={result.items}
        initialTotalCount={result.totalCount}
        initialPage={result.page}
        initialPageSize={result.pageSize}
        initialPageCount={result.pageCount}
        initialSettings={result.settings ?? deepdexSettingsDefaults}
        initialErrorMessage={result.errorMessage}
      />
    </CustomerPageShell>
  );
}
