export function coerceDate(value: unknown): Date | null {
  if (value instanceof Date) {
    return Number.isNaN(value.getTime()) ? null : value
  }

  if (value === null || value === undefined) {
    return null
  }

  const fromNumber = (raw: number): Date | null => {
    if (Number.isNaN(raw)) {
      return null
    }

    const ms = raw < 1e12 ? raw * 1000 : raw
    const date = new Date(ms)
    return Number.isNaN(date.getTime()) ? null : date
  }

  if (typeof value === 'number') {
    return fromNumber(value)
  }

  if (typeof value === 'bigint') {
    return fromNumber(Number(value))
  }

  if (typeof value === 'string') {
    const trimmed = value.trim()
    if (!trimmed) {
      return null
    }

    const numeric = Number(trimmed)
    if (!Number.isNaN(numeric)) {
      return fromNumber(numeric)
    }

    const parsed = Date.parse(trimmed)
    if (!Number.isNaN(parsed)) {
      return new Date(parsed)
    }
  }

  if (typeof value === 'object') {
    const record = value as { value?: unknown; valueOf?: () => unknown; toString?: () => string }
    if (record.value !== undefined) {
      return coerceDate(record.value)
    }

    if (record.valueOf) {
      const valueOf = record.valueOf()
      if (valueOf !== value) {
        return coerceDate(valueOf)
      }
    }

    if (record.toString) {
      const asString = record.toString()
      if (asString && asString !== '[object Object]') {
        return coerceDate(asString)
      }
    }
  }

  return null
}
