// 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 { Warranty } 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
  qty: string
  unitCost: string
  discountPct: string
  vatPct: string
  warranty: Warranty | null
  warrantyNumbers: string[]
}): Record<string, string> {
  const errors: Record<string, string> = {}

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

  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.warranty === "Warranty") {
    const numbers = input.warrantyNumbers.map((s) => s.trim()).filter((s) => s.length > 0)
    if (numbers.length === 0) {
      errors.warrantyNumbers = "Enter one warranty number per unit"
    } else if (!Number.isNaN(qty) && numbers.length !== qty) {
      errors.warrantyNumbers = `Enter exactly ${qty || 0} warranty number(s) — got ${numbers.length}`
    } else if (new Set(numbers.map((s) => s.toLowerCase())).size !== numbers.length) {
      errors.warrantyNumbers = "Warranty numbers must be unique"
    }
  }

  return errors
}
