import { ExchangeRate } from "@/db/models";
import { AppError } from "@/lib/errors";
import { isMysqlActive } from "@/db/activeDatabase";
import type { RowDataPacket } from "mysql2/promise";
import { connectMysql, mysqlPool, sqlQuery } from "@/db/mysql/pool";

async function getActiveExchangeRateMysql(fromCurrency: string, toCurrency: string) {
  try {
    mysqlPool();
  } catch {
    await connectMysql();
  }
  const now = new Date();
  const rows = await sqlQuery<RowDataPacket[]>(
    `SELECT * FROM exchange_rates
     WHERE from_currency = ? AND to_currency = ?
       AND (valid_to IS NULL OR valid_to > ?)
     ORDER BY valid_from DESC
     LIMIT 1`,
    [fromCurrency, toCurrency, now],
  );
  const r = rows[0];
  if (!r) return null;
  return {
    _id: String(r.id),
    id: String(r.id),
    fromCurrency: String(r.from_currency),
    toCurrency: String(r.to_currency),
    rate: Number(r.rate),
    validFrom: new Date(r.valid_from),
    validTo: r.valid_to ? new Date(r.valid_to) : null,
  };
}

export async function getActiveExchangeRate(fromCurrency: string, toCurrency: string) {
  if (isMysqlActive()) {
    const rate = await getActiveExchangeRateMysql(fromCurrency, toCurrency);
    if (!rate) {
      throw new AppError(500, `No active exchange rate for ${fromCurrency}/${toCurrency}`);
    }
    return rate;
  }

  const now = new Date();
  const rate = await ExchangeRate.findOne({
    fromCurrency,
    toCurrency,
    $or: [{ validTo: null }, { validTo: { $exists: false } }, { validTo: { $gt: now } }],
  })
    .sort({ validFrom: -1 })
    .lean();

  if (!rate) {
    throw new AppError(500, `No active exchange rate for ${fromCurrency}/${toCurrency}`);
  }
  return rate;
}
