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
}

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

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