import { redirect } from "next/navigation";
import DashboardPage from "./dashboard/page";

export const dynamic = "force-dynamic";

type SearchParams = Promise<Record<string, string | string[] | undefined>>;

function first(value: string | string[] | undefined) {
  return Array.isArray(value) ? value[0] : value;
}

export default async function HomePage({ searchParams }: { searchParams: SearchParams }) {
  const params = await searchParams;
  const code = first(params.code);
  const shopId = first(params.shop_id);
  const mainAccountId = first(params.main_account_id);

  if (code && (shopId || mainAccountId)) {
    const callbackParams = new URLSearchParams({ code });
    if (shopId) callbackParams.set("shop_id", shopId);
    if (mainAccountId) callbackParams.set("main_account_id", mainAccountId);
    redirect(`/api/shopee/callback?${callbackParams.toString()}`);
  }

  return <DashboardPage searchParams={Promise.resolve({ shop_id: shopId })} />;
}
