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

export const dynamic = "force-dynamic";

export default async function AdminAssemblyDetailPage({
  params,
}: {
  params: Promise<{ id: string; assemblyId: string }>;
}) {
  const { id, assemblyId } = await params;
  const assembly = await prisma.assembly.findFirst({
    where: { id: assemblyId, projectId: id },
    include: {
      project: { select: { id: true, code: true, name: true } },
      stepFile: true,
      drawingFile: true,
      cutFile: true,
      parts: {
        orderBy: { code: "asc" },
        include: {
          _count: { select: { operations: true } },
          stepFile: { select: { id: true } },
          drawingFile: { select: { id: true } },
          cutFile: { select: { id: true } },
          thumbnailFile: { select: { id: true } },
        },
      },
    },
  });
  if (!assembly) notFound();

  const fileView = (f: typeof assembly.stepFile) =>
    f
      ? {
          id: f.id,
          originalName: f.originalName,
          sizeBytes: f.sizeBytes,
          kind: f.kind,
          mimeType: f.mimeType,
        }
      : null;

  return (
    <AssemblyDetailClient
      project={assembly.project}
      assembly={{
        id: assembly.id,
        code: assembly.code,
        name: assembly.name,
        qty: assembly.qty,
        notes: assembly.notes,
        stepFile: fileView(assembly.stepFile),
        drawingFile: fileView(assembly.drawingFile),
        cutFile: fileView(assembly.cutFile),
      }}
      parts={assembly.parts.map((p) => ({
        id: p.id,
        code: p.code,
        name: p.name,
        material: p.material,
        qty: p.qty,
        hasStep: !!p.stepFile,
        hasDrawing: !!p.drawingFile,
        hasCut: !!p.cutFile,
        thumbnailFileId: p.thumbnailFile?.id ?? null,
        operationCount: p._count.operations,
      }))}
    />
  );
}
