import { z } from "zod";

export const receiptLineInputSchema = z.object({
  purchase_line_id: z.string().trim().min(1, "Purchase line wajib ada"),
  grade_id: z.string().trim().optional().nullable().or(z.literal("")),
  qty_received: z.coerce.number().nonnegative("Qty received tidak boleh negatif"),
  qty_accepted: z.coerce.number().nonnegative("Qty accepted tidak boleh negatif"),
  qty_rejected: z.coerce.number().nonnegative("Qty rejected tidak boleh negatif"),
  unit_id: z.string().trim().min(1, "Unit wajib dipilih"),
  unit_cost: z.coerce.number().nonnegative("Unit cost tidak boleh negatif"),
  warehouse_id: z.string().trim().min(1, "Warehouse wajib dipilih"),
  warehouse_location_id: z.string().trim().optional().nullable(),
  notes: z.string().trim().optional().or(z.literal(""))
}).superRefine((line, ctx) => {
  if (line.qty_accepted + line.qty_rejected > line.qty_received) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ["qty_accepted"],
      message: "Qty accepted + rejected tidak boleh melebihi qty received"
    });
  }
});

export const receiptInputSchema = z.object({
  purchase_id: z.string().trim().min(1, "Purchase wajib dipilih"),
  receipt_date: z.string().trim().min(1, "Tanggal receipt wajib diisi"),
  notes: z.string().trim().optional().or(z.literal("")),
  lines: z.array(receiptLineInputSchema).min(1, "Minimal satu line receipt")
});
