function toIsoTimestamp(value) {
  if (value == null || value === '') return null

  const numeric = Number(value)
  const date = Number.isFinite(numeric)
    ? new Date(Math.abs(numeric) < 1e12 ? numeric * 1000 : numeric)
    : new Date(value)

  return Number.isNaN(date.getTime()) ? null : date.toISOString()
}

export function normalizeSkillTimestamps(skill) {
  return {
    ...skill,
    created_at: toIsoTimestamp(skill?.created_at),
    updated_at: toIsoTimestamp(skill?.updated_at),
  }
}

function timestampParts(value, timeZone = 'Asia/Shanghai') {
  if (!value) return null
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return null
  const parts = new Intl.DateTimeFormat('en-CA', {
    timeZone,
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hourCycle: 'h23',
  }).formatToParts(date)
  return Object.fromEntries(parts.map(part => [part.type, part.value]))
}

export function formatSkillDate(value, timeZone = 'Asia/Shanghai') {
  const parts = timestampParts(value, timeZone)
  return parts ? `${parts.year}-${parts.month}-${parts.day}` : '—'
}

export function formatSkillDateTime(value, timeZone = 'Asia/Shanghai') {
  const parts = timestampParts(value, timeZone)
  return parts
    ? `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}:${parts.second}`
    : '—'
}
