import { fromZonedTime } from 'date-fns-tz';

const WINDOWS_TO_IANA_TIMEZONE: Record<string, string> = {
  UTC: 'UTC',
  'Dateline Standard Time': 'Etc/GMT+12',
  'UTC-11': 'Pacific/Pago_Pago',
  'Aleutian Standard Time': 'America/Adak',
  'Hawaiian Standard Time': 'Pacific/Honolulu',
  'Alaskan Standard Time': 'America/Anchorage',
  'Pacific Standard Time': 'America/Los_Angeles',
  'Pacific Standard Time (Mexico)': 'America/Tijuana',
  'Mountain Standard Time': 'America/Denver',
  'US Mountain Standard Time': 'America/Phoenix',
  'Central Standard Time': 'America/Chicago',
  'Central Standard Time (Mexico)': 'America/Mexico_City',
  'Eastern Standard Time': 'America/New_York',
  'US Eastern Standard Time': 'America/Indianapolis',
  'SA Pacific Standard Time': 'America/Bogota',
  'Atlantic Standard Time': 'America/Halifax',
  'Argentina Standard Time': 'America/Buenos_Aires',
  'E. South America Standard Time': 'America/Sao_Paulo',
  'GMT Standard Time': 'Europe/London',
  'W. Europe Standard Time': 'Europe/Berlin',
  'Romance Standard Time': 'Europe/Paris',
  'Central Europe Standard Time': 'Europe/Budapest',
  'South Africa Standard Time': 'Africa/Johannesburg',
  'Russian Standard Time': 'Europe/Moscow',
  'Arabian Standard Time': 'Asia/Dubai',
  'India Standard Time': 'Asia/Kolkata',
  'SE Asia Standard Time': 'Asia/Bangkok',
  'China Standard Time': 'Asia/Shanghai',
  'Singapore Standard Time': 'Asia/Singapore',
  'Tokyo Standard Time': 'Asia/Tokyo',
  'Korea Standard Time': 'Asia/Seoul',
  'AUS Eastern Standard Time': 'Australia/Sydney',
  'New Zealand Standard Time': 'Pacific/Auckland',
};

export function normalizeToIanaTimezone(timezone: string | undefined, fallback = 'UTC'): string {
  const raw = timezone?.trim();
  if (!raw) {
    return fallback;
  }
  if (raw.includes('/')) {
    return raw;
  }
  return WINDOWS_TO_IANA_TIMEZONE[raw] || fallback;
}

export function convertToUTC(localDateTime: string, timezone: string): Date {
  const normalized = normalizeToIanaTimezone(timezone, 'UTC');
  try {
    return fromZonedTime(localDateTime, normalized);
  } catch {
    return new Date(localDateTime);
  }
}
