import { cookies, headers } from "next/headers";
import { notFound, redirect } from "next/navigation";
import { WaitClient } from "@/components/wait-client";
import { VpnBlocked } from "@/components/vpn-blocked";
import { getSetting } from "@/lib/earnings";
import { localeFromRequest } from "@/lib/geo-locale";
import { getClientIp } from "@/lib/request";
import { findTarget } from "@/lib/targets";
import { loadUiMessages } from "@/lib/ui-messages";
import { isVpnOrProxy } from "@/lib/vpn";

export default async function ShortPage({
  params,
}: {
  params: Promise<{ code: string }>;
}) {
  const { code } = await params;
  const target = await findTarget(code);
  if (!target) notFound();

  const jar = await cookies();
  const headerList = await headers();
  const { locale, wait } = await loadUiMessages(
    await localeFromRequest(headerList, jar.get("NEXT_LOCALE")?.value),
  );
  const ip = getClientIp(headerList);
  if (await isVpnOrProxy(ip)) {
    return (
      <VpnBlocked title={wait.vpnTitle} body={wait.vpnBody} dir={locale === "ar" ? "rtl" : "ltr"} />
    );
  }

  if (target.monetization === "FREE") {
    redirect(`/api/go/${code}`);
  }
  const seconds = Number(await getSetting("countdownSeconds", "5"));
  return (
    <WaitClient
      code={code}
      seconds={seconds}
      isFile={target.kind === "FILE"}
      messages={wait}
      dir={locale === "ar" ? "rtl" : "ltr"}
    />
  );
}
