const { z } = require("zod")

const normalizeStringValue = (value) => {
  if (value === undefined || value === null) return null
  if (typeof value !== "string") return value
  const trimmed = value.trim()
  return trimmed === "" ? null : trimmed
}

const optionalTrimmedString = () =>
  z.preprocess((value) => normalizeStringValue(value), z.string().or(z.null()))

const optionalUrlString = () =>
  z.preprocess(
    (value) => {
      const normalized = normalizeStringValue(value)
      return normalized === null ? null : normalized
    },
    z.string().url().or(z.null())
  )

const optionalPrice = () =>
  z.preprocess(
    (value) => {
      if (value === undefined || value === null) return null
      if (typeof value === "string") {
        const normalized = value.replace(",", ".").trim()
        return normalized === "" ? null : Number(normalized)
      }
      return value
    },
    z.number().nonnegative().or(z.null())
  )

module.exports = {
  normalizeStringValue,
  optionalTrimmedString,
  optionalUrlString,
  optionalPrice,
}
