import axios from 'axios'
import type { IpInfo } from '../../shared/types'

export class IpService {
  private cache: IpInfo | null = null
  private cacheTime: number = 0
  private cacheDuration = 5 * 60 * 1000 // 5 minutes

  async getIpInfo(): Promise<IpInfo> {
    // Return cached data if still valid
    if (this.cache && Date.now() - this.cacheTime < this.cacheDuration) {
      return this.cache
    }

    try {
      // Try ip-api.com first (more detailed info, free)
      const response = await axios.get('http://ip-api.com/json/', {
        timeout: 10000,
        params: {
          fields: 'status,message,country,countryCode,city,isp,query,timezone'
        }
      })

      if (response.data.status === 'success') {
        const info: IpInfo = {
          ip: response.data.query,
          country: response.data.country,
          countryCode: response.data.countryCode,
          city: response.data.city,
          isp: response.data.isp,
          timezone: response.data.timezone
        }
        
        this.cache = info
        this.cacheTime = Date.now()
        return info
      }
    } catch (error) {
      console.error('ip-api.com failed:', error)
    }

    // Fallback to ipify + ipapi
    try {
      const ipResponse = await axios.get('https://api.ipify.org?format=json', {
        timeout: 10000
      })
      const ip = ipResponse.data.ip

      const geoResponse = await axios.get(`https://ipapi.co/${ip}/json/`, {
        timeout: 10000
      })

      const info: IpInfo = {
        ip: ip,
        country: geoResponse.data.country_name || 'Unknown',
        countryCode: geoResponse.data.country_code || 'XX',
        city: geoResponse.data.city,
        isp: geoResponse.data.org,
        timezone: geoResponse.data.timezone
      }

      this.cache = info
      this.cacheTime = Date.now()
      return info
    } catch (error) {
      console.error('Fallback IP lookup failed:', error)
      throw new Error('Failed to get IP information')
    }
  }

  clearCache(): void {
    this.cache = null
    this.cacheTime = 0
  }
}

