import { getReservationTimeZone, reservationTimeZone } from '@/config/reservationConfig'

export function formatReservationDateTime(value: string | null | undefined): string {
  if (!value) {
    return '-'
  }
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) {
    return value
  }
  return formatDateTimeInTimeZone(date, getReservationTimeZone())
}

export function formatReservationDateRange(arrivalDate: string, departureDate: string): string {
  return `${arrivalDate} / ${departureDate}`
}

export function formatReservationCurrency(amount: number, currencyCode: string): string {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: currencyCode,
    maximumFractionDigits: 0,
  }).format(amount)
}

function formatDateTimeInTimeZone(date: Date, timeZone: string): string {
  try {
    return formatDateTimeParts(date, timeZone)
  } catch {
    return formatDateTimeParts(date, reservationTimeZone)
  }
}

function formatDateTimeParts(date: Date, timeZone: string): string {
  const parts = new Intl.DateTimeFormat('en-GB', {
    timeZone,
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hourCycle: 'h23',
  }).formatToParts(date)
  const valueByType = Object.fromEntries(parts.map((part) => [part.type, part.value]))
  return `${valueByType.year}-${valueByType.month}-${valueByType.day} ${valueByType.hour}:${valueByType.minute}:${valueByType.second}`
}
