/**
 * Timezone Utilities
 * Handles conversion between UTC and IST (Indian Standard Time)
 */

/**
 * Convert UTC ISO string to IST
 * @param utcIsoString - UTC timestamp in ISO format (e.g., "2026-03-04T10:30:45.123Z")
 * @returns Date object in IST timezone
 */
export function utcToIST(utcIsoString: string): Date {
  return new Date(utcIsoString)
}

/**
 * Format a UTC ISO timestamp as IST
 * @param utcIsoString - UTC timestamp in ISO format
 * @param format - Format type: 'date', 'time', 'datetime', 'full'
 * @returns Formatted string in IST
 */
export function formatIST(
  utcIsoString: string,
  format: 'date' | 'time' | 'datetime' | 'full' = 'datetime'
): string {
  const date = new Date(utcIsoString)

  // IST is UTC+5:30
  const istDate = new Date(date.getTime() + 5.5 * 60 * 60 * 1000)

  switch (format) {
    case 'date':
      return istDate.toLocaleDateString('en-IN', {
        year: 'numeric',
        month: 'short',
        day: '2-digit',
      }).toUpperCase()

    case 'time':
      return istDate.toLocaleTimeString('en-IN', {
        hour: '2-digit',
        minute: '2-digit',
        hour12: false,
      }).toUpperCase()

    case 'datetime':
      return istDate.toLocaleString('en-IN', {
        year: 'numeric',
        month: 'short',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false,
      }).toUpperCase()

    case 'full':
      return istDate.toLocaleString('en-IN', {
        weekday: 'short',
        year: 'numeric',
        month: 'short',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false,
      }).toUpperCase()

    default:
      return istDate.toISOString()
  }
}

/**
 * Get IST date components from UTC ISO string
 * @param utcIsoString - UTC timestamp in ISO format
 * @returns Object with date components in IST
 */
export function getISTDateComponents(utcIsoString: string) {
  const date = new Date(utcIsoString)
  const istDate = new Date(date.getTime() + 5.5 * 60 * 60 * 1000)

  return {
    year: istDate.getUTCFullYear(),
    month: istDate.getUTCMonth(),
    date: istDate.getUTCDate(),
    day: istDate.getUTCDay(),
    hours: istDate.getUTCHours(),
    minutes: istDate.getUTCMinutes(),
    seconds: istDate.getUTCSeconds(),
  }
}

/**
 * Format date as YYYY-MM-DD (IST)
 * @param utcIsoString - UTC timestamp in ISO format
 * @returns Date string in YYYY-MM-DD format (IST)
 */
export function formatISTDateOnly(utcIsoString: string): string {
  const date = new Date(utcIsoString)
  const istDate = new Date(date.getTime() + 5.5 * 60 * 60 * 1000)

  const year = istDate.getUTCFullYear()
  const month = String(istDate.getUTCMonth() + 1).padStart(2, '0')
  const day = String(istDate.getUTCDate()).padStart(2, '0')

  return `${year}-${month}-${day}`
}
