import { z } from "zod";

export const jitSaleCreateSchema = z
  .object({
    sale_date: z.string().trim().min(1, "Tanggal penjualan wajib diisi"),
    buyer_id: z.string().trim().min(1, "Buyer wajib dipilih"),
    buyer_currency_code: z.string().trim().min(1, "Mata uang buyer wajib dipilih"),
    company_currency_code: z.string().trim().min(1, "Mata uang perusahaan wajib dipilih"),
    exchange_rate: z.coerce.number().nullable().optional(),
    courier_id: z.string().trim().optional().nullable().or(z.literal("")),
    shipping_cost_buyer: z.coerce.number().min(0, "Biaya kirim tidak boleh negatif"),
    notes: z.string().trim().max(2000).optional().nullable(),
    lines: z
      .array(
        z.object({
          grade_id: z.string().trim().min(1, "Grade wajib dipilih"),
          qty_planned: z.coerce.number().positive("Quantity harus lebih besar dari 0"),
          mal_unit_price: z.coerce.number().min(0, "Harga MAL tidak boleh negatif"),
          selling_price_planned: z.coerce.number().min(0, "Harga jual tidak boleh negatif"),
          agent_id: z.string().trim().optional().nullable().or(z.literal("")),
          profit_share_scheme_id: z.string().trim().optional().nullable().or(z.literal("")),
          notes: z.string().trim().max(500).optional().nullable()
        })
      )
      .min(1, "Minimal satu barang harus dipilih")
  })
  .superRefine((payload, ctx) => {
    const buyerCurrency = payload.buyer_currency_code.trim().toUpperCase();
    const companyCurrency = payload.company_currency_code.trim().toUpperCase();

    if (buyerCurrency !== companyCurrency && (!payload.exchange_rate || payload.exchange_rate <= 0)) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ["exchange_rate"],
        message: "Rate wajib diisi saat mata uang buyer dan perusahaan berbeda"
      });
    }

    payload.lines.forEach((line, index) => {
      if (line.agent_id && !line.profit_share_scheme_id) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: ["lines", index, "profit_share_scheme_id"],
          message: "Skema bagi hasil wajib dipilih jika line memakai agen"
        });
      }
    });
  });

export const jitSaleCloseSchema = z.object({
  close_date: z.string().trim().min(1, "Tanggal penyelesaian wajib diisi"),
  lines: z
    .array(
      z.object({
        line_id: z.string().trim().min(1, "Line wajib dikirim"),
        selling_price_actual: z.coerce.number().min(0, "Harga jual aktual tidak boleh negatif")
      })
    )
    .min(1, "Seluruh item penjualan harus dikirim saat close")
});

export type JitSaleCreateInput = z.infer<typeof jitSaleCreateSchema>;
export type JitSaleCloseInput = z.infer<typeof jitSaleCloseSchema>;
