import { notFound } from 'next/navigation';
import { prisma } from '@/lib/prisma';
import { PostForm } from '@/components/admin/post-form';
import type { Locale } from '@/i18n/config';

export default async function EditPostPage({
  params: { locale, id }
}: {
  params: { locale: Locale; id: string };
}) {
  const [post, authors, tags] = await Promise.all([
    prisma.post.findUnique({ where: { id }, include: { translations: true, tags: true } }),
    prisma.author.findMany({ include: { translations: { where: { locale: 'fr' } } } }),
    prisma.tag.findMany({ include: { translations: { where: { locale: 'fr' } } } })
  ]);
  if (!post) notFound();

  const fr = post.translations.find((t) => t.locale === 'fr');
  const ar = post.translations.find((t) => t.locale === 'ar');

  return (
    <div>
      <h1 className="font-display text-2xl font-semibold">Modifier l'article</h1>
      <div className="mt-6">
        <PostForm
          locale={locale}
          authors={authors.map((a) => ({ id: a.id, name: a.translations[0]?.name ?? a.slug }))}
          tags={tags.map((t) => ({ id: t.id, name: t.translations[0]?.name ?? t.slug }))}
          initial={{
            id: post.id,
            authorId: post.authorId,
            tagIds: post.tags.map((t) => t.id),
            coverImage: post.coverImage ?? undefined,
            featured: post.featured,
            published: post.published,
            readingMinutes: post.readingMinutes,
            fr: fr ? { title: fr.title, excerpt: fr.excerpt, content: fr.content } : undefined,
            ar: ar ? { title: ar.title, excerpt: ar.excerpt, content: ar.content } : undefined
          }}
        />
      </div>
    </div>
  );
}
