import { z } from "zod";

export const mobileLotTransformationSchema = z.object({
  transformation_type: z.enum(["MIX", "REGRADE"]).default("MIX"),
  transformation_date: z.string().min(1, "Tanggal transformasi wajib diisi"),
  remainder_mode: z.enum(["KEEP_SOURCE_GRADE", "SHRINKAGE"]).optional().nullable(),
  processing_loss_mode: z.enum(["SHRINKAGE"]).optional().nullable(),
  notes: z.string().trim().max(2000).optional().nullable(),
  inputs: z
    .array(
      z.object({
        source_lot_code: z.string().trim().min(1, "Lot code wajib diisi"),
        qty_used: z.coerce.number().positive("Qty used harus lebih dari 0"),
        notes: z.string().trim().max(500).optional().nullable()
      })
    )
    .min(1, "Minimal satu lot sumber"),
  outputs: z
    .array(
      z.object({
        grade_id: z.string().min(1, "Grade wajib dipilih"),
        warehouse_id: z.string().min(1, "Warehouse wajib dipilih"),
        warehouse_location_id: z.string().trim().optional().nullable(),
        qty_produced: z.coerce.number().positive("Qty produced harus lebih dari 0"),
        notes: z.string().trim().max(500).optional().nullable()
      })
    )
    .min(1, "Minimal satu lot hasil")
}).superRefine((value, ctx) => {
  if (value.transformation_type === "REGRADE" && value.inputs.length !== 1) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ["inputs"],
      message: "Regrade harus memakai tepat satu source lot"
    });
  }

  if (value.transformation_type === "MIX" && value.inputs.length < 2) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ["inputs"],
      message: "Mix minimal memakai dua source lot"
    });
  }

  const seen = new Set<string>();
  value.inputs.forEach((input, index) => {
    const normalized = input.source_lot_code.trim().toUpperCase();
    if (seen.has(normalized)) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ["inputs", index, "source_lot_code"],
        message: "Lot sumber tidak boleh duplikat"
      });
    }
    seen.add(normalized);
  });
});

export type MobileLotTransformationPayload = z.infer<typeof mobileLotTransformationSchema>;
