import { NextResponse } from "next/server";

import { createLotTransformation } from "@/features/lot-transformations/lib/create-lot-transformation";
import { serializeLotTransformationListItem } from "@/features/lot-transformations/lib/serialize-transformation";
import { lotTransformationSchema } from "@/features/lot-transformations/schemas/lot-transformation.schema";
import { requireApiAccess } from "@/lib/authorization";
import { prisma } from "@/lib/prisma";

export async function GET(request: Request) {
  const auth = requireApiAccess(request);
  if (!auth.ok) return auth.response;

  const items = await prisma.lotTransformation.findMany({
    include: {
      inputs: { select: { qtyUsed: true } },
      outputs: { select: { qtyProduced: true } }
    },
    orderBy: [{ transformationDate: "desc" }, { createdAt: "desc" }]
  });

  return NextResponse.json({
    data: items.map(serializeLotTransformationListItem)
  });
}

export async function POST(request: Request) {
  const auth = requireApiAccess(request);
  if (!auth.ok) return auth.response;

  const body = await request.json();
  const parsed = lotTransformationSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      {
        message: "Validasi gagal",
        errors: parsed.error.flatten().fieldErrors
      },
      { status: 422 }
    );
  }

  return createLotTransformation({
    payload: parsed.data,
    actorUserId: auth.user.id,
    requestMethod: request.method,
    pathname: new URL(request.url).pathname
  });
}
