/**
 * 外部入口落地页（Server Component）
 *
 * 外部应用可以通过 query 传入 Facebook 相关信息和最终目标页，例如：
 * `/external-entry?target=chat&asid=xxx&psid=yyy`
 * `/external-entry?target=chat&mode=promotion&promotion_type=voice`
 * `/external-entry?target=chat&character=maya`
 * `/external-entry?target=tip`
 * `/external-entry?target=private-zone&character=nayeli`
 *
 * 页面不直接 `redirect()`，而是把数据交给 Client 组件先写入本地存储，
 * 再通过 `router.replace()` 清理 URL 并跳转到最终页面。
 */

import ExternalEntryPersist from "./external-entry-persist";

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

interface ExternalEntryPageProps {
  searchParams: SearchParams;
}

export default async function ExternalEntryPage({
  searchParams,
}: ExternalEntryPageProps) {
  const params = await searchParams;

  return (
    <ExternalEntryPersist
      deviceId={pickParam(params.device_id)}
      asid={pickParam(params.asid)}
      psid={pickParam(params.psid)}
      avatarUrl={pickParam(params.avatar_url)}
      target={pickParam(params.target)}
      character={pickParam(params.character)}
      mode={pickParam(params.mode)}
      promotionType={pickParam(params.promotion_type)}
      favorite={pickParam(params.favorite)}
    />
  );
}

function pickParam(value: string | string[] | undefined): string | null {
  if (Array.isArray(value)) {
    return value.find((item) => item.trim().length > 0) ?? null;
  }
  return value && value.trim().length > 0 ? value : null;
}
