// Client-side UX validation only (docs/20-FRONTEND.md §3.1) — required fields,
// format/range checks the browser can already see. Server-authoritative rules
// (over-receipt tolerance, referential existence, concurrency) are never
// re-implemented here; the server's ProblemDetails is the final word (§3.3).
import { z } from "zod"
import { TrackingMode } from "@/types/master-data"

export const grnHeaderSchema = z.object({
  warehouseId: z.number({ error: "Select a warehouse" }).positive("Select a warehouse"),
  vendorId: z.number().nullable(),
  poId: z.number().nullable(),
})

export function validateLine(input: {
  itemId: number | null
  uomId: number | null
  qty: string
  unitCost: string
  discountPct: string
  vatPct: string
  trackingMode: TrackingMode | null
  batchNo: string
  serialNumbersText: string
}): Record<string, string> {
  const errors: Record<string, string> = {}

  if (!input.itemId) errors.itemId = "Select an item"
  if (!input.uomId) errors.uomId = "Select a UOM"

  const qty = Number(input.qty)
  if (!input.qty || Number.isNaN(qty) || qty <= 0) errors.qty = "Quantity must be greater than 0"

  const unitCost = Number(input.unitCost)
  if (input.unitCost === "" || Number.isNaN(unitCost) || unitCost < 0) errors.unitCost = "Unit cost cannot be negative"

  const discountPct = Number(input.discountPct)
  if (input.discountPct !== "" && (Number.isNaN(discountPct) || discountPct < 0 || discountPct > 100))
    errors.discountPct = "Discount must be 0–100%"

  const vatPct = Number(input.vatPct)
  if (input.vatPct !== "" && (Number.isNaN(vatPct) || vatPct < 0 || vatPct > 100))
    errors.vatPct = "VAT must be 0–100%"

  if (input.trackingMode === "Batch" && !input.batchNo.trim()) {
    errors.batchNo = "Batch number is required for this item"
  }

  if (input.trackingMode === "Serial") {
    const serials = splitSerials(input.serialNumbersText)
    if (serials.length === 0) {
      errors.serialNumbers = "Enter one serial number per unit"
    } else if (!Number.isNaN(qty) && serials.length !== qty) {
      errors.serialNumbers = `Enter exactly ${qty || 0} serial number(s) — got ${serials.length}`
    } else if (new Set(serials).size !== serials.length) {
      errors.serialNumbers = "Serial numbers must be unique"
    }
  }

  return errors
}

export function splitSerials(text: string): string[] {
  return text
    .split(/[\n,]/)
    .map((s) => s.trim())
    .filter((s) => s.length > 0)
}
