/** Shared IP / geo helpers for admin display + session storage */

export type IpGeoFields = {
  ip_address?: string | null
  flag?: string | null
  country?: string | null
  country_code?: string | null
  region?: string | null
  city?: string | null
  isp?: string | null
  timezone?: string | null
}

/**
 * Compact admin line:
 * `1.2.3.4 ~ 🇦🇱 ~ Albania ~ Tirana County ~ Tirana ~ Vodafone`
 */
export function formatIpGeoLine(session: IpGeoFields, options?: { includeTimezone?: boolean }): string {
  const parts = [
    session.ip_address?.trim() || '—',
    session.flag?.trim(),
    session.country?.trim(),
    session.region?.trim(),
    session.city?.trim(),
    session.isp?.trim(),
  ]
  if (options?.includeTimezone) {
    parts.push(session.timezone?.trim())
  }
  return parts.filter((p): p is string => Boolean(p)).join(' ~ ')
}

export type IpLocationResponse = {
  country: string
  countryCode: string
  flag: string
  city?: string
  region?: string
  isp?: string
  org?: string
  asn?: string
  timezone?: string
}

export function locationToSessionColumns(loc: IpLocationResponse) {
  return {
    country: loc.country || null,
    country_code: loc.countryCode || null,
    flag: loc.flag || null,
    city: loc.city || null,
    region: loc.region || null,
    isp: loc.isp || loc.org || loc.asn || null,
    timezone: loc.timezone || null,
  }
}
