import { get } from '@/lib/api-client';
import { getCurrentLocale } from '@/lib/i18n';

export interface PlaceSearchResult {
  latitude: number;
  longitude: number;
  displayName: string;
  title: string;
}

const reverseCache = new Map<string, string>();

export function clearReverseCache() {
  reverseCache.clear();
}

function buildKey(lat: number, lon: number): string {
  return `${lat.toFixed(5)},${lon.toFixed(5)},${getCurrentLocale()}`;
}

function getLang(): string {
  const locale = getCurrentLocale();
  return locale === 'zh' ? 'zh-CN,zh,en' : 'en,zh-CN,zh';
}

/**
 * 搜索地点 — 走后端代理
 */
export async function searchPlaces(query: string): Promise<PlaceSearchResult[]> {
  if (!query.trim()) return [];

  try {
    const data = await get<{ places: PlaceSearchResult[] }>(
      '/site-attendance/checkpoints/code/geocode/search',
      { params: { q: query.trim(), lang: getLang() } },
    );
    return data.places;
  } catch {
    return [];
  }
}

/**
 * 反向地理编码 — 走后端代理，语言跟随前端 locale
 */
export async function reverseGeocode(latitude: number, longitude: number): Promise<string> {
  if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) {
    return '';
  }

  const key = buildKey(latitude, longitude);
  const cached = reverseCache.get(key);
  if (cached) return cached;

  try {
    const data = await get<{ displayName: string }>(
      '/site-attendance/checkpoints/code/geocode/reverse',
      { params: { lat: String(latitude), lon: String(longitude), lang: getLang() } },
    );
    const name = data.displayName || `${latitude.toFixed(5)}, ${longitude.toFixed(5)}`;
    reverseCache.set(key, name);
    return name;
  } catch {
    return `${latitude.toFixed(5)}, ${longitude.toFixed(5)}`;
  }
}
