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

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

const getMemorial = unstable_cache(
  async (subdomain: string) => {
    const user = await prisma.user.findUnique({
      where: { subdomain },
      include: { images: { orderBy: { order: "asc" } } },
    });
    return user;
  },
  ["memorial"],
  { revalidate: 3600, tags: ["memorial"] }
);

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { subdomain } = await params;
  const user = await getMemorial(subdomain);

  if (!user || !user.published) {
    return { title: "Спомен страницата не е пронајдена" };
  }

  const title = user.title || "Спомен";
  const description = user.description?.slice(0, 160) || `Во спомен на ${title}`;

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

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

  const user = await getMemorial(subdomain);

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

  const data = {
    id: user.id,
    title: user.title,
    description: user.description,
    bornDate: user.bornDate,
    passedDate: user.passedDate,
    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);
}