import { ClmDashboardPageClient } from "@/components/clm/clm-dashboard-page-client";
import { getViewerContext } from "@/lib/auth";
import { getClmDashboardData, getClmWorkbookSnapshot } from "@/lib/clm-dashboard";
import { getClmFilterParams, resolveDashboardScope } from "@/lib/dashboard-request";
import { release } from "@/lib/release";
import { notFound } from "next/navigation";

export default async function ClmDashboardPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  if (!release.clmEnabled) {
    notFound();
  }

  const viewer = await getViewerContext();
  const params = await searchParams;
  const query = new URLSearchParams();

  for (const [key, rawValue] of Object.entries(params)) {
    const value = Array.isArray(rawValue) ? rawValue[0] : rawValue;
    if (typeof value === "string" && value) {
      query.set(key, value);
    }
  }

  const { activeScope, scopeCountries } = resolveDashboardScope(viewer, query.get("scope") ?? "");
  const filters = getClmFilterParams(query);
  const data = await getClmDashboardData(filters, scopeCountries);
  const workbookSnapshot = await getClmWorkbookSnapshot(filters, scopeCountries);

  return (
    <ClmDashboardPageClient
      initialQuery={query.toString()}
      initialPayload={{ activeScope, data, workbookSnapshot }}
    />
  );
}
