import { prisma } from "@/lib/prisma";
import { renderTemplate } from "@/lib/templates";
import type { Metadata } from "next";
import { notFound } from "next/navigation";

interface Props {
  params: Promise<{ subdomain: string }>;
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { subdomain } = await params;
  const user = await prisma.user.findUnique({
    where: { subdomain },
    include: { images: { orderBy: { order: "asc" } } },
  });

  if (!user || !user.published) {
    return { title: "Monument Not Found" };
  }

  const title = user.title || "City Monument";
  const description = user.description?.slice(0, 160) || `Visit ${title} — a monument page on SpomeniQR.`;

  return {
    title,
    description,
    openGraph: {
      title,
      description,
      images: user.images[0]?.url ? [{ url: user.images[0].url }] : undefined,
      type: "article",
    },
  };
}

export default async function MonumentPage({ params }: Props) {
  const { subdomain } = await params;

  const user = await prisma.user.findUnique({
    where: { subdomain },
    include: { images: { orderBy: { order: "asc" } } },
  });

  if (!user || !user.published) {
    notFound();
  }

  const data = {
    id: user.id,
    title: user.title,
    description: user.description,
    subdomain: user.subdomain,
    templateId: user.templateId,
    published: user.published,
    images: user.images.map((img) => ({
      id: img.id,
      url: img.url,
      key: img.key,
      order: img.order,
    })),
  };

  return renderTemplate(user.templateId, data);
}