// GCC Country currency mappings
export const GCC_CURRENCIES = {
  SA: 'SAR', // Saudi Arabia
  AE: 'AED', // United Arab Emirates
  QA: 'QAR', // Qatar
  KW: 'KWD', // Kuwait
  BH: 'BHD', // Bahrain
  OM: 'OMR', // Oman
} as const

export type CountryCode = keyof typeof GCC_CURRENCIES
export type CurrencyCode = typeof GCC_CURRENCIES[CountryCode]

// Default currency if country cannot be detected
export const DEFAULT_CURRENCY: CurrencyCode = 'SAR'

// Get user's country from IP using ipapi.co free service
export async function getUserCountry(): Promise<CountryCode | null> {
  try {
    const response = await fetch('https://ipapi.co/json/', {
      next: { revalidate: 3600 }, // Cache for 1 hour
    })

    if (!response.ok) {
      return null
    }

    const data = await response.json()
    const countryCode = data.country_code as string

    // Check if it's a GCC country
    if (countryCode in GCC_CURRENCIES) {
      return countryCode as CountryCode
    }

    return null
  } catch (error) {
    console.error('Failed to get user country:', error)
    return null
  }
}

// Get currency based on country code
export function getCurrencyForCountry(countryCode: CountryCode | null): CurrencyCode {
  if (!countryCode || !(countryCode in GCC_CURRENCIES)) {
    return DEFAULT_CURRENCY
  }
  return GCC_CURRENCIES[countryCode]
}

// Format price with currency
export function formatPrice(amount: number, currency: CurrencyCode): string {
  return `${amount.toLocaleString()} ${currency}`
}

// Get user's currency based on IP location
export async function getUserCurrency(): Promise<CurrencyCode> {
  const country = await getUserCountry()
  return getCurrencyForCountry(country)
}