import type { JsonObject } from '../../types/json.js'
export function normalizePage(rawValue: unknown) {
  const parsed = Number(rawValue)
  return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 1
}

export function normalizePageSize(rawValue: unknown) {
  const parsed = Number(rawValue)
  if (!Number.isFinite(parsed) || parsed <= 0) {
    return 20
  }
  return Math.min(100, Math.floor(parsed))
}

export function normalizeDateQuery(rawValue: unknown, endOfDay = false) {
  const normalized = String(rawValue || '').trim()

  if (!normalized) {
    return ''
  }

  if (/^\d{4}-\d{2}-\d{2}$/.test(normalized)) {
    return endOfDay ? `${normalized}T23:59:59.999Z` : `${normalized}T00:00:00.000Z`
  }

  return normalized
}

/** 校验并归一化 YYYY-MM-DD 日期参数，非法或空值返回空字符串。 */
export function normalizeDateString(rawValue: unknown) {
  const normalized = String(rawValue || '').trim()
  return /^\d{4}-\d{2}-\d{2}$/.test(normalized) ? normalized : ''
}

/**
 * 校验并归一化日期时间参数：YYYY-MM-DD 或 YYYY-MM-DD HH:mm[:ss]。
 * 纯日期原样返回（SQL 侧按当天零点处理），缺秒补 :00；非法或空值返回空字符串。
 */
export function normalizeDateTimeString(rawValue: unknown) {
  const normalized = String(rawValue || '').trim()
  if (!normalized) {
    return ''
  }
  if (/^\d{4}-\d{2}-\d{2}$/.test(normalized)) {
    return normalized
  }
  const match = normalized.match(/^(\d{4}-\d{2}-\d{2}) (\d{2}):(\d{2})(?::(\d{2}))?$/)
  if (!match) {
    return ''
  }
  const [, datePart, hour, minute, second] = match
  // roundtrip 校验拦截 2026-02-31 这类会被 Date 溢出成其他日期的非法值
  const parsedDate = new Date(`${datePart}T00:00:00Z`)
  if (Number.isNaN(parsedDate.getTime()) || parsedDate.toISOString().slice(0, 10) !== datePart) {
    return ''
  }
  if (Number(hour) > 23 || Number(minute) > 59 || Number(second ?? '0') > 59) {
    return ''
  }
  return `${datePart} ${hour}:${minute}:${second ?? '00'}`
}

export function safeParseJson(rawText: unknown): JsonObject {
  if (rawText && typeof rawText === 'object') {
    return rawText
  }

  try {
    return JSON.parse(String(rawText || '{}'))
  } catch {
    return {}
  }
}
