import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
import POClient from "./POClient";

export const dynamic = "force-dynamic";

export default async function POPage({
  params,
}: {
  params: Promise<{ id: string; poId: string }>;
}) {
  const { id: projectId, poId } = await params;
  const project = await prisma.project.findUnique({
    where: { id: projectId },
    select: { id: true, code: true, name: true },
  });
  if (!project) notFound();

  const po = await prisma.purchaseOrder.findUnique({
    where: { id: poId },
    include: {
      lines: {
        include: {
          fastener: {
            select: {
              id: true,
              partNumber: true,
              description: true,
              supplier: true,
              unitCost: true,
            },
          },
        },
      },
    },
  });
  if (!po || po.projectId !== projectId) notFound();

  return (
    <POClient
      project={project}
      po={{
        id: po.id,
        vendor: po.vendor,
        status: po.status,
        createdAt: po.createdAt.toISOString(),
        sentAt: po.sentAt?.toISOString() ?? null,
        receivedAt: po.receivedAt?.toISOString() ?? null,
        notes: po.notes,
      }}
      lines={po.lines.map((l) => ({
        id: l.id,
        fastener: l.fastener,
        qty: l.qty,
        receivedQty: l.receivedQty,
        unitCost: l.unitCost,
      }))}
    />
  );
}
