import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { api } from "@/lib/api";
import { buildMetadata, buildProductJsonLd, type ItemCondition } from "@/lib/seo";
import { ItemDetailClient } from "./item-detail-client";

interface ItemDetailPageProps {
  params: Promise<{ id: string }>;
}

export async function generateMetadata({ params }: ItemDetailPageProps): Promise<Metadata> {
  const { id } = await params;

  try {
    const res = await api.items.getPublic(id);
    const item = res.data;
    const titleParts = [item.title];
    if (item.brand) titleParts.push(item.brand);
    const descriptorParts = [item.brand, item.condition, item.category?.name].filter(
      (part): part is string => Boolean(part),
    );
    const fallbackDescription = descriptorParts.length
      ? `${descriptorParts.join(" · ")} — shop ${item.title} on Alqove.`
      : `Shop ${item.title} on Alqove.`;
    const description = item.description
      ? item.description.length > 160
        ? item.description.slice(0, 157) + "..."
        : item.description
      : fallbackDescription;

    return buildMetadata({
      title: titleParts.join(" — "),
      description,
      image: item.images?.[0]?.url ?? undefined,
      canonical: `https://alqove.com/items/${id}`,
    });
  } catch {
    return buildMetadata({
      title: "Item not found",
      description: "This item may have been sold or removed.",
      noindex: true,
    });
  }
}

export default async function ItemDetailPage({ params }: ItemDetailPageProps) {
  const { id } = await params;

  let item;
  try {
    const res = await api.items.getPublic(id);
    item = res.data;
  } catch {
    notFound();
  }

  const jsonLd = buildProductJsonLd(
    {
      id: item.id,
      title: item.title,
      description: item.description ?? "",
      brand: item.brand ?? null,
      condition: item.condition as ItemCondition,
      price: item.price,
      imageUrl: item.images?.[0]?.url ?? null,
      status: item.status ?? null,
      sellerName: item.store?.name ?? null,
    },
    `https://alqove.com/items/${id}`,
  );

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />
      <ItemDetailClient item={item} />
    </>
  );
}
