import { redirect } from "next/navigation";
import { requireAccount } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { ContactDetail } from "@/components/contacts/contact-detail";

export const dynamic = "force-dynamic";

export default async function ContactDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const membership = await requireAccount();
  const { id } = await params;

  const [contact, tags, fields] = await Promise.all([
    prisma.contact.findFirst({
      where: { id, accountId: membership.account.id },
      include: {
        tags: { include: { tag: true } },
        customValues: { include: { field: true } },
        notes: { include: { author: { select: { name: true } } }, orderBy: { createdAt: "desc" } },
        conversations: { include: { messages: { orderBy: { createdAt: "desc" }, take: 1 } } },
        deals: { include: { pipeline: true, stage: true } },
      },
    }),
    prisma.tag.findMany({ where: { accountId: membership.account.id }, orderBy: { name: "asc" } }),
    prisma.customFieldDef.findMany({ where: { accountId: membership.account.id }, orderBy: { name: "asc" } }),
  ]);

  if (!contact) redirect("/contacts");
  return <ContactDetail contact={contact} tags={tags} fields={fields} />;
}