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

export const dynamic = "force-dynamic";

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

  const pos = await prisma.purchaseOrder.findMany({
    where: { projectId: id },
    orderBy: [{ createdAt: "desc" }],
    include: {
      lines: {
        select: {
          qty: true,
          receivedQty: true,
          unitCost: true,
          fastener: { select: { unitCost: true } },
        },
      },
    },
  });

  // Same "unresolved" suggestion for new drafts that /fasteners uses.
  const fasteners = await prisma.fastener.findMany({
    where: { projectId: id },
    orderBy: [{ supplier: "asc" }, { partNumber: "asc" }],
    include: {
      poLines: {
        select: { qty: true, po: { select: { status: true } } },
      },
    },
  });
  const fastenerOptions = fasteners.map((f) => {
    let onOrder = 0;
    for (const l of f.poLines) {
      if (l.po.status === "cancelled") continue;
      onOrder += l.qty;
    }
    return {
      id: f.id,
      partNumber: f.partNumber,
      description: f.description,
      supplier: f.supplier,
      unitCost: f.unitCost,
      qty: f.qty,
      unresolved: Math.max(0, f.qty - onOrder),
    };
  });

  const rows = pos.map((po) => {
    const totalQty = po.lines.reduce((a, l) => a + l.qty, 0);
    const totalReceived = po.lines.reduce((a, l) => a + l.receivedQty, 0);
    const totalCost = po.lines.reduce((acc, l) => {
      const cost = l.unitCost ?? l.fastener.unitCost ?? 0;
      return acc + cost * l.qty;
    }, 0);
    return {
      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,
      lineCount: po.lines.length,
      totalQty,
      totalReceived,
      totalCost,
    };
  });

  return (
    <PurchaseOrdersClient project={project} initial={rows} fastenerOptions={fastenerOptions} />
  );
}
