/**
 * Quick verification: live Frankfurter API → DB upsert → getRate read.
 * Run with `pnpm tsx scripts/test-currency-api.ts`.
 */
import { refreshRates, getRate, convert } from '@/lib/services/currency';

async function main() {
  console.log('1. Fetching live rates from Frankfurter…');
  await refreshRates();

  console.log('2. Reading round-trip rates from DB:');
  const usdEur = await getRate('USD', 'EUR');
  const eurUsd = await getRate('EUR', 'USD');
  const usdGbp = await getRate('USD', 'GBP');
  const eurGbp = await getRate('EUR', 'GBP');
  const usdUsd = await getRate('USD', 'USD');

  console.log(`  USD→EUR: ${usdEur}`);
  console.log(`  EUR→USD: ${eurUsd}`);
  console.log(`  USD→GBP: ${usdGbp}`);
  console.log(`  EUR→GBP: ${eurGbp ?? '(no direct row, expected)'}`);
  console.log(`  USD→USD: ${usdUsd}`);

  console.log('3. Convert sample amounts:');
  const c1 = await convert(1000, 'USD', 'EUR');
  console.log(`  $1000 → ${c1?.result} EUR @ ${c1?.rate}`);
  const c2 = await convert(500, 'EUR', 'USD');
  console.log(`  €500 → $${c2?.result} @ ${c2?.rate}`);

  // Sanity: EUR→USD should be ≈ 1 / (USD→EUR), within rounding
  if (usdEur && eurUsd) {
    const drift = Math.abs(eurUsd - 1 / usdEur);
    console.log(`4. Inverse-rate drift: ${drift.toFixed(6)} (≤0.001 = healthy)`);
  }

  process.exit(0);
}

main().catch((err) => {
  console.error('Currency test failed:', err);
  process.exit(1);
});
