import { NextResponse } from "next/server";

import { createLotTransformation } from "@/features/lot-transformations/lib/create-lot-transformation";
import { mobileLotTransformationSchema } from "@/features/mobile/schemas/mobile-lot-transformation.schema";
import { requireApiAccess } from "@/lib/authorization";
import { prisma } from "@/lib/prisma";
export { GET } from "@/app/api/v1/lot-transformations/route";

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

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

  const normalizedCodes = parsed.data.inputs.map((input) => input.source_lot_code.trim().toUpperCase());
  const sourceLots = await prisma.inventoryLot.findMany({
    where: {
      lotCode: {
        in: normalizedCodes
      }
    },
    select: {
      id: true,
      lotCode: true
    }
  });

  const lotCodeMap = new Map(sourceLots.map((lot) => [lot.lotCode.toUpperCase(), lot.id.toString()]));
  const missingCodes = normalizedCodes.filter((code) => !lotCodeMap.has(code));
  if (missingCodes.length > 0) {
    return NextResponse.json(
      {
        message: "Sebagian lot sumber tidak ditemukan",
        errors: {
          inputs: missingCodes.map((code) => `Lot ${code} tidak ditemukan`)
        }
      },
      { status: 404 }
    );
  }

  return createLotTransformation({
    payload: {
      transformation_type: parsed.data.transformation_type,
      transformation_date: parsed.data.transformation_date,
      remainder_mode: parsed.data.remainder_mode ?? null,
      processing_loss_mode: parsed.data.processing_loss_mode ?? null,
      notes: parsed.data.notes ?? null,
      inputs: parsed.data.inputs.map((input) => ({
        source_lot_id: lotCodeMap.get(input.source_lot_code.trim().toUpperCase())!,
        qty_used: input.qty_used,
        notes: input.notes ?? null
      })),
      outputs: parsed.data.outputs.map((output) => ({
        grade_id: output.grade_id,
        warehouse_id: output.warehouse_id,
        warehouse_location_id: output.warehouse_location_id ?? null,
        qty_produced: output.qty_produced,
        notes: output.notes ?? null
      }))
    },
    actorUserId: auth.user.id,
    requestMethod: request.method,
    pathname: new URL(request.url).pathname
  });
}
