/**
 * OpenAPI 클라이언트
 * - 외부 API(날씨, 환율 등) 호출
 */

import { apiClient } from './client';

// ============================================================
// 타입 정의
// ============================================================

/**
 * 날씨 정보
 */
export interface WeatherData {
  city: string;
  country: string;
  lat?: number;
  lng?: number;
  temperature: number;
  feelsLike: number;
  humidity: number;
  pressure: number;
  weatherMain: string;
  weatherDescription: string;
  weatherIcon: string;
  windSpeed: number;
  clouds: number;
  timestamp: string;
}

/**
 * 환율 정보
 */
export interface ExchangeRateData {
  base: string;
  target: string;
  rate: number;
  timestamp: string;
}

/**
 * Geocoding 결과
 */
export interface GeocodeData {
  address: string;
  lat: number;
  lng: number;
}

/**
 * API 응답 타입
 */
interface ApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
}

// ============================================================
// API 함수
// ============================================================

/**
 * 날씨 정보 조회
 * @param city 도시명 (기본값: Seoul)
 * @param units 단위 (metric: 섭씨, imperial: 화씨)
 * @param lang 언어 (kr: 한국어, en: 영어)
 */
export async function getWeather(
  city: string = '서울',
  units: string = 'metric',
  lang: string = 'kr'
): Promise<WeatherData> {
  const response = await apiClient.get<ApiResponse<WeatherData>>(
    `/open-api/weather`,
    {
      params: { city, units, lang },
    }
  );
  return response.data.data;
}

/**
 * 여러 도시의 날씨 정보 일괄 조회
 * @param cities 도시명 배열
 */
export async function getMultipleWeather(cities: string[]): Promise<WeatherData[]> {
  const promises = cities.map(city => getWeather(city));
  return Promise.all(promises);
}

/**
 * 기상특보 정보 조회
 */
export interface WeatherAlert {
  id: string;
  type: string;
  severity: "high" | "medium" | "low";
  title: string;
  location: string;
  description: string;
  timestamp: string;
  polygon?: { lat: number; lng: number }[]; // 폴리곤 경계 좌표
  center?: { lat: number; lng: number }; // 중심점 좌표
}

export async function getWeatherAlerts(): Promise<WeatherAlert[]> {
  const response = await apiClient.get<WeatherAlert[]>("/risk-alerts/weather");
  return response.data;
}

/**
 * 환율 정보 조회
 * @param base 기준 통화 (기본값: KRW)
 * @param target 대상 통화 (기본값: USD)
 */
export async function getExchangeRate(
  base: string = 'KRW',
  target: string = 'USD'
): Promise<ExchangeRateData> {
  const response = await apiClient.get<ApiResponse<ExchangeRateData>>(
    `/open-api/exchange-rate`,
    {
      params: { base, target },
    }
  );
  return response.data.data;
}

/**
 * 주소를 좌표로 변환 (Geocoding)
 * @param address 주소
 */
export async function geocode(address: string): Promise<GeocodeData> {
  const response = await apiClient.post<ApiResponse<GeocodeData>>(
    `/open-api/geocode`,
    { address }
  );
  return response.data.data;
}

