import { prisma } from "@/lib/prisma";
import ProjectsPageClient from "@/app/_ui/ProjectsPageClient";
import type { Metadata } from "next";
import { getLanguageAlternates, toAbsoluteUrl } from "@/lib/seo";

export const revalidate = 300;

export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string }>;
}): Promise<Metadata> {
  const { locale } = await params;
  const languages = getLanguageAlternates({ pathWithoutLocale: "projects" });
  return {
    alternates: {
      canonical: toAbsoluteUrl(`/${locale}/projects`),
      languages,
    },
  };
}

export default async function ProjectsPage({
  params,
}: {
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;

  const projects = await prisma.project.findMany({
    where: { published: true },
    orderBy: { createdAt: "desc" },
    include: {
      translations: {
        select: { title: true, description: true, locale: true },
      },
    },
  });

  const localized = projects.map((p) => {
    const trPreferred = p.translations?.find((t) => t.locale === locale && (t?.title || t?.description));
    const trDefault = p.translations?.find(
      (t) => t.locale === p.defaultLocale && (t?.title || t?.description),
    );
    const tr = trPreferred ?? trDefault;
    const { translations: _translations, ...rest } = p;
    return {
      ...rest,
      title: tr?.title ?? p.title,
      description: tr?.description ?? p.description,
    };
  });

  return <ProjectsPageClient projects={localized} locale={locale} />;
}

