import { db } from '@/lib/db';
import { currencyRates } from '@/lib/db/schema/system';
import { eq, and } from 'drizzle-orm';
import { logger } from '@/lib/logger';

export async function getRate(from: string, to: string): Promise<number | null> {
  if (from === to) return 1;
  const rate = await db.query.currencyRates.findFirst({
    where: and(eq(currencyRates.baseCurrency, from), eq(currencyRates.targetCurrency, to)),
  });
  return rate ? Number(rate.rate) : null;
}

export async function convert(
  amount: number,
  from: string,
  to: string,
): Promise<{ result: number; rate: number } | null> {
  const rate = await getRate(from, to);
  if (!rate) return null;
  return { result: Number((amount * rate).toFixed(2)), rate };
}

export async function refreshRates(): Promise<void> {
  try {
    const res = await fetch('https://api.frankfurter.dev/v1/latest?base=USD');
    if (!res.ok) throw new Error(`Frankfurter API error: ${res.status}`);
    const data = await res.json();
    const rates = data.rates as Record<string, number>;

    for (const [currency, rate] of Object.entries(rates)) {
      await db
        .insert(currencyRates)
        .values({
          baseCurrency: 'USD',
          targetCurrency: currency,
          rate: String(rate),
          source: 'frankfurter',
          fetchedAt: new Date(),
        })
        .onConflictDoUpdate({
          target: [currencyRates.baseCurrency, currencyRates.targetCurrency],
          set: { rate: String(rate), fetchedAt: new Date(), source: 'frankfurter' },
        });
    }

    // Store inverse rates for common conversions
    for (const [currency, rate] of Object.entries(rates)) {
      const inverse = 1 / rate;
      await db
        .insert(currencyRates)
        .values({
          baseCurrency: currency,
          targetCurrency: 'USD',
          rate: String(inverse.toFixed(6)),
          source: 'frankfurter',
          fetchedAt: new Date(),
        })
        .onConflictDoUpdate({
          target: [currencyRates.baseCurrency, currencyRates.targetCurrency],
          set: { rate: String(inverse.toFixed(6)), fetchedAt: new Date(), source: 'frankfurter' },
        });
    }

    logger.info({ rateCount: Object.keys(rates).length }, 'Currency rates refreshed');
  } catch (err) {
    logger.error({ err }, 'Failed to refresh currency rates');
  }
}
