import axios from 'axios';
import { getApiBaseUrl } from './apiConfig';

// API 베이스 URL (통합 설정 사용)
const API_BASE_URL = getApiBaseUrl().replace('/api', ''); // /api 제거

/**
 * 즐겨찾기 암호화폐 DTO
 */
export interface CryptoFavoriteDto {
  id?: number;
  symbol: string;
  koreanName: string;
  englishName?: string;
  displayOrder?: number;
  createdAt?: string;
}

/**
 * 모든 즐겨찾기 조회
 */
export const getAllFavorites = async (): Promise<CryptoFavoriteDto[]> => {
  const response = await axios.get(`${API_BASE_URL}/api/favorites`);
  return response.data;
};

/**
 * 심볼로 즐겨찾기 조회
 */
export const getFavoriteBySymbol = async (symbol: string): Promise<CryptoFavoriteDto | null> => {
  try {
    const response = await axios.get(`${API_BASE_URL}/api/favorites/${symbol}`);
    return response.data;
  } catch (error: any) {
    if (error.response?.status === 404) {
      return null;
    }
    throw error;
  }
};

/**
 * 즐겨찾기 존재 여부 확인
 */
export const checkFavorite = async (symbol: string): Promise<boolean> => {
  const response = await axios.get(`${API_BASE_URL}/api/favorites/check/${symbol}`);
  return response.data.isFavorite;
};

/**
 * 즐겨찾기 추가
 */
export const addFavorite = async (dto: CryptoFavoriteDto): Promise<CryptoFavoriteDto> => {
  const response = await axios.post(`${API_BASE_URL}/api/favorites`, dto);
  return response.data;
};

/**
 * 즐겨찾기 삭제
 */
export const removeFavorite = async (symbol: string): Promise<void> => {
  await axios.delete(`${API_BASE_URL}/api/favorites/${symbol}`);
};

/**
 * 즐겨찾기 토글 (추가/삭제)
 */
export const toggleFavorite = async (dto: CryptoFavoriteDto): Promise<boolean> => {
  const response = await axios.post(`${API_BASE_URL}/api/favorites/toggle`, dto);
  return response.data.isFavorite;
};

/**
 * 즐겨찾기 순서 변경
 */
export const updateDisplayOrder = async (id: number, displayOrder: number): Promise<void> => {
  await axios.put(`${API_BASE_URL}/api/favorites/${id}/order`, { displayOrder });
};
