import geoip from 'geoip-lite';
import type { GeoLocation } from '../types.js';

export const lookupByIP = (ip: string): GeoLocation | null => {
  if (!ip || ip === '::1' || ip === '127.0.0.1') {
    return null;
  }

  const result = geoip.lookup(ip);
  if (!result) return null;

  return {
    latitude: result.ll?.[0] ?? 0,
    longitude: result.ll?.[1] ?? 0,
    country: result.country ?? '',
    countryCode: result.country ?? '',
    region: result.region ?? '',
    city: result.city ?? '',
    timezone: result.timezone ?? '',
    source: 'ip',
  };
};
