import type { Metadata } from "next";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";

import { softLaunchAdminCookieDigest } from "@/server/soft-launch-admin-digest";

export const runtime = "nodejs";

export const metadata: Metadata = {
  title: "Soft launch — tổng hợp vận hành",
  robots: { index: false, follow: false },
};

export default async function SoftLaunchSummaryPage({
  searchParams,
}: {
  searchParams: Promise<{ hours?: string }>;
}) {
  const { hours: hoursQ } = await searchParams;
  const hours = hoursQ ? Number.parseInt(hoursQ, 10) : 24;
  const h = Number.isFinite(hours) ? Math.min(168, Math.max(1, hours)) : 24;

  const envSecret = process.env.SOFT_LAUNCH_ADMIN_SECRET?.trim();
  if (!envSecret) {
    return (
      <main className="min-h-[50dvh] bg-stone-950 p-8 text-stone-200">
        <p>Chưa cấu hình SOFT_LAUNCH_ADMIN_SECRET trên máy chủ web.</p>
      </main>
    );
  }
  const jar = await cookies();
  const token = jar.get("ctkp_sl_adm")?.value;
  if (token !== softLaunchAdminCookieDigest(envSecret)) {
    redirect(`/internal/soft-launch/login?next=${encodeURIComponent("/internal/soft-launch/summary")}`);
  }

  const api = process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/$/, "");
  if (!api) {
    return (
      <main className="min-h-[50dvh] bg-stone-950 p-8 text-stone-200">
        <p>Chưa cấu hình NEXT_PUBLIC_API_BASE_URL.</p>
      </main>
    );
  }

  const res = await fetch(`${api}/soft-launch/admin/summary?hours=${h}`, {
    headers: { "X-Soft-Launch-Admin-Secret": envSecret },
    cache: "no-store",
  });

  if (!res.ok) {
    return (
      <main className="min-h-[50dvh] bg-stone-950 p-8 text-stone-200">
        <p>
          Lỗi {res.status} khi tải summary — kiểm tra migration soft launch và secret trùng backend.
        </p>
      </main>
    );
  }

  const json = (await res.json()) as Record<string, unknown>;

  return (
    <main className="min-h-[100dvh] bg-stone-950 px-4 py-10 text-stone-100">
      <div className="mx-auto max-w-3xl space-y-6">
        <h1 className="font-sans text-xl text-stone-50">Tổng hợp beta (nội bộ)</h1>
        <p className="font-sans text-xs text-stone-500">
          Cửa sổ: <span className="text-stone-300">{String(json.windowHours ?? h)}</span> giờ ·{" "}
          <a className="text-amber-200 underline" href="?hours=24">
            24h
          </a>{" "}
          ·{" "}
          <a className="text-amber-200 underline" href="?hours=72">
            72h
          </a>
        </p>
        <pre className="overflow-auto rounded border border-stone-800 bg-stone-900/80 p-4 font-mono text-[11px] leading-relaxed text-emerald-100/90">
          {JSON.stringify(json, null, 2)}
        </pre>
      </div>
    </main>
  );
}
