/**
 * Currency Service
 * API client for currency exchange endpoints
 */

import { apiClient } from '../lib/apiClient';

// ============================================================================
// Types
// ============================================================================

export interface ExchangeRate {
  fromCurrency: string;
  toCurrency: string;
  rate: number;
  source: string;
  updatedAt: string;
}

export interface ConversionRequest {
  amount: number;
  fromCurrency: string;
  toCurrency: string;
}

export interface ConversionResult {
  originalAmount: number;
  convertedAmount: number;
  rate: number;
  fromCurrency: string;
  toCurrency: string;
}

export interface UpdateRateRequest {
  fromCurrency: string;
  toCurrency: string;
  rate: number;
  source?: string;
  provider?: string;
  metadata?: Record<string, unknown>;
}

// ============================================================================
// API Client
// ============================================================================

const api = apiClient;

// ============================================================================
// Currency Exchange API
// ============================================================================

/**
 * Get exchange rate between two currencies
 */
export async function getRate(from: string, to: string): Promise<ExchangeRate> {
  try {
    const response = await api.get(`/currency/rates/${from}/${to}`);
    return response.data.data || response.data;
  } catch (error) {
    console.error('Failed to fetch exchange rate:', error);
    throw new Error('Failed to fetch exchange rate');
  }
}

/**
 * Get all exchange rates for a base currency
 */
export async function getExchangeRates(baseCurrency: string): Promise<ExchangeRate[]> {
  try {
    const response = await api.get(`/currency/rates/${baseCurrency}`);
    return response.data.data || response.data;
  } catch (error) {
    console.error('Failed to fetch exchange rates:', error);
    throw new Error('Failed to fetch exchange rates');
  }
}

/**
 * Convert amount between currencies
 */
export async function convert(
  amount: number,
  from: string,
  to: string
): Promise<ConversionResult> {
  try {
    const response = await api.post('/currency/convert', {
      amount,
      fromCurrency: from,
      toCurrency: to,
    });
    return response.data.data || response.data;
  } catch (error) {
    console.error('Failed to convert currency:', error);
    throw new Error('Failed to convert currency');
  }
}

/**
 * Get list of supported currencies
 * Extracts unique currencies from exchange rates
 */
export async function getSupportedCurrencies(baseCurrency: string = 'USD'): Promise<string[]> {
  try {
    const rates = await getExchangeRates(baseCurrency);
    const currencies = new Set<string>();

    // Add base currency
    currencies.add(baseCurrency.toUpperCase());

    // Add all currencies from rates
    for (const rate of rates) {
      currencies.add(rate.fromCurrency.toUpperCase());
      currencies.add(rate.toCurrency.toUpperCase());
    }

    return Array.from(currencies).sort();
  } catch (error) {
    console.error('Failed to fetch supported currencies:', error);
    throw new Error('Failed to fetch supported currencies');
  }
}

/**
 * Update exchange rate (admin only)
 */
export async function updateRate(request: UpdateRateRequest): Promise<ExchangeRate> {
  try {
    const response = await api.put('/currency/rates', request);
    return response.data.data || response.data;
  } catch (error) {
    console.error('Failed to update exchange rate:', error);
    throw new Error('Failed to update exchange rate');
  }
}

// ============================================================================
// Export
// ============================================================================

export const currencyService = {
  getRate,
  getExchangeRates,
  convert,
  getSupportedCurrencies,
  updateRate,
};

export default currencyService;
