const { z } = require("zod")

const { normalizeStringValue } = require("./common")

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

const parsePositiveInteger = (rawValue) => {
  if (rawValue === undefined || rawValue === null || rawValue === "") return undefined
  const candidate =
    typeof rawValue === "string" ? rawValue.trim() : rawValue
  if (candidate === "") return undefined
  const integerValue = Number(candidate)
  return Number.isInteger(integerValue) ? integerValue : rawValue
}

const pageSchema = z
  .preprocess((value) => parsePositiveInteger(value), z.number().int().min(1).max(1000000))
  .default(1)

const limitSchema = z
  .preprocess((value) => parsePositiveInteger(value), z.number().int().min(1).max(100))
  .default(10)

const dealListQuerySchema = z.object({
  q: z
    .preprocess(
      (value) => normalizeQueryString(value),
      z.string().max(200, { message: "Arama sorgusu 200 karakteri geçemez" })
    )
    .default(""),
  page: pageSchema,
  limit: limitSchema,
})

module.exports = {
  dealListQuerySchema,
}
