// code -> user-facing message (docs/20-FRONTEND.md §3.2: "Keep a code -> message
// map in lib/ so messages are consistent"). Falls back to the ProblemDetails
// title/detail from the server when a code isn't in the map.

interface ApiErrorLike {
  code?: string
  detail?: string
  errors?: Record<string, string[]>
}

const CODE_MESSAGES: Record<string, string> = {
  OVER_RECEIPT_TOLERANCE: "This quantity exceeds the purchase order's open quantity beyond the allowed tolerance.",
  STOCK_NEGATIVE_BLOCKED: "Not enough available stock for this action.",
  EXPIRED_BATCH_BLOCKED: "This batch has expired and cannot be issued.",
  ONHOLD_NOT_ISSUABLE: "This stock is on hold/quarantined and cannot be issued.",
  REASON_CODE_REQUIRED: "A reason code is required for this action.",
  PO_NOT_EDITABLE: "This purchase order can no longer be edited.",
  SKU_DUPLICATE: "That SKU already exists.",
  MASTER_IN_USE: "This record is referenced by other data and cannot be deleted.",
  CONCURRENCY_CONFLICT: "This record was changed by someone else. Reload and try again.",
  PRECONDITION_REQUIRED: "This record needs to be reloaded before it can be updated.",
  IDEMPOTENCY_REPLAY: "This request was already processed; showing the original result.",
  validation_error: "Please check the highlighted fields.",
  not_found: "The requested record was not found.",
  conflict: "This action conflicts with the record's current state.",
}

export function errorMessage(error: unknown): string {
  if (error && typeof error === "object") {
    const e = error as ApiErrorLike
    if (e.code && CODE_MESSAGES[e.code]) return CODE_MESSAGES[e.code]
    if (e.detail) return e.detail
  }
  if (error instanceof Error) return error.message
  return "Something went wrong."
}

export function fieldErrors(error: unknown): Record<string, string> | null {
  const errors = error && typeof error === "object" ? (error as ApiErrorLike).errors : undefined
  if (!errors) return null
  const out: Record<string, string> = {}
  for (const [field, messages] of Object.entries(errors)) {
    out[field] = messages[0]
  }
  return out
}
