import { requireAuth } from '@/server/utils/auth';
import { refreshExchangeRates } from '@/server/utils/currency';

export default defineEventHandler(async (event) => {
  await requireAuth(event);
  
  console.log('[currency/refresh] Manual exchange rate refresh requested');
  
  try {
    const result = await refreshExchangeRates();
    
    if (result.success) {
      console.log('[currency/refresh] Exchange rates refreshed successfully');
      return {
        success: true,
        message: result.message,
        ratesCount: result.ratesCount,
        timestamp: new Date().toISOString()
      };
    } else {
      console.error('[currency/refresh] Failed to refresh exchange rates:', result.message);
      throw createError({
        statusCode: 500,
        statusMessage: result.message
      });
    }
  } catch (error: any) {
    console.error('[currency/refresh] Error during refresh:', error);
    
    throw createError({
      statusCode: 500,
      statusMessage: error.message || 'Failed to refresh exchange rates'
    });
  }
});
