import { logger } from "../../lib/logger";
import { prisma } from "../../lib/prisma";
import { roundTo, startOfToday } from "../../lib/utils";

interface BeloApiResponse {
  ask: number;
  bid: number;
  totalAsk: number;
  totalBid: number;
  time: number;
}

export async function fetchBeloQuote(): Promise<{ buy: number; sell: number }> {
  const response = await fetch("https://criptoya.com/api/belo/USDC/ARS/1");
  const data: BeloApiResponse = await response.json();
  return { buy: data.bid, sell: data.ask };
}

export async function processBeloQuote(): Promise<void> {
  const { buy, sell } = await fetchBeloQuote();

  const existingQuote = await prisma.quote.findFirst({
    where: { type: "BELO" },
  });

  if (!existingQuote) {
    await prisma.quote.create({
      data: {
        buy,
        sell,
        type: "BELO",
        difference: 0,
        percentage: 0,
        previousDayDifference: 0,
        previousDayPercentage: 0,
      },
    });
    await prisma.quoteHistory.create({
      data: { buy, sell, type: "BELO" },
    });
    return;
  }

  const existingSell = Number(existingQuote.sell);
  const diff = roundTo(sell - existingSell, 2);
  const pct = existingSell !== 0 ? roundTo((diff / existingSell) * 100, 2) : 0;

  logger.debug({ buy, sell, diferencia: diff, porcentaje: pct }, `Cotización BELO`);

  const todayStart = startOfToday();

  const prevDayHistory = await prisma.quoteHistory.findFirst({
    where: {
      type: "BELO",
      timeStamp: { lt: todayStart },
    },
    orderBy: { timeStamp: "desc" },
  });

  let prevDayDiff = 0;
  let prevDayPct = 0;
  if (prevDayHistory) {
    const prevSell = Number(prevDayHistory.sell);
    prevDayDiff = roundTo(sell - prevSell, 2);
    prevDayPct = prevSell !== 0 ? roundTo((prevDayDiff / prevSell) * 100, 2) : 0;
  }

  await prisma.quote.update({
    where: { id: existingQuote.id },
    data: {
      buy,
      sell,
      timeStamp: new Date(),
      difference: diff,
      percentage: pct,
      previousDayDifference: prevDayDiff,
      previousDayPercentage: prevDayPct,
    },
  });

  await prisma.quoteHistory.create({
    data: { buy, sell, type: "BELO" },
  });
}
