import type { Metadata } from "next";
import LabelDetailClient from "./LabelDetail";
import { getLabelById, getLabelAuthoredEntries, getLabelPublishedEntries } from "@/server/repo";

export async function generateMetadata({ params }: { params: Promise<{ id: string }> }): Promise<Metadata> {
  const { id } = await params;
  const label = await getLabelById(Number(id));
  if (!label) return { title: "Label Not Found | ZXDB" };
  return { title: `${label.name} | ZXDB Label` };
}

// Depends on searchParams (?page=, ?tab=). Force dynamic so each request renders correctly.
export const dynamic = "force-dynamic";

export default async function Page({ params, searchParams }: { params: Promise<{ id: string }>;
  searchParams: Promise<{ [key: string]: string | string[] | undefined }> }) {
  const [{ id }, sp] = await Promise.all([params, searchParams]);
  const numericId = Number(id);
  const page = Math.max(1, Number(Array.isArray(sp.page) ? sp.page[0] : sp.page) || 1);
  const tab = (Array.isArray(sp.tab) ? sp.tab[0] : sp.tab) as "authored" | "published" | undefined;
  const q = (Array.isArray(sp.q) ? sp.q[0] : sp.q) ?? "";
  const [label, authored, published] = await Promise.all([
    getLabelById(numericId),
    getLabelAuthoredEntries(numericId, { page, pageSize: 20, q: q || undefined }),
    getLabelPublishedEntries(numericId, { page, pageSize: 20, q: q || undefined }),
  ]);

  // Let the client component handle the "not found" simple state
  return <LabelDetailClient id={numericId} initial={{ label: label, authored: authored, published: published }} initialTab={tab} initialQ={q} />;
}
