import { cookies } from "next/headers";
import MatcherPageClient from "./MatcherPageClient";
import { MATCH_CONFIGS } from "./constants";
import { getMatcherData } from "@/app/services/matcher";
import { getBaseUrl } from "@/app/services/constants";

export default async function MatcherPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const params = await searchParams;
  const matchType =
    (params.type as string) || Object.keys(MATCH_CONFIGS)[0] || "";

  const baseUrl = getBaseUrl();

  // Forward cookies for auth when calling the internal API route
  const cookieStore = await cookies();
  const cookieHeader = cookieStore
    .getAll()
    .map((c: { name: string; value: string }) => `${c.name}=${c.value}`)
    .join("; ");

  const { sourceItems, targetItems } = await getMatcherData(
    matchType,
    cookieHeader,
    baseUrl
  );

  const config =
    MATCH_CONFIGS[matchType] || MATCH_CONFIGS[Object.keys(MATCH_CONFIGS)[0]];

  return (
    <MatcherPageClient
      initialSourceItems={sourceItems}
      initialTargetItems={targetItems}
      initialMatchType={matchType}
      config={config}
    />
  );
}
