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

interface DolaritoApiResponse {
  oficial: {
    buy: number;
    sell: number;
  };
}

export async function fetchBnaQuote(): Promise<{ buy: number; sell: number }> {
  const response = await fetch("https://api.dolarito.ar/api/frontend/quotations/dolar", {
    credentials: "omit",
    headers: {
      "User-Agent":
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:139.0) Gecko/20100101 Firefox/139.0",
      Accept: "application/json, text/plain, */*",
      "Accept-Language": "es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3",
      "auth-client": "a4b981d93266b37ea6a646f5b3538f8a",
      "Sec-Fetch-Dest": "empty",
      "Sec-Fetch-Mode": "cors",
      "Sec-Fetch-Site": "same-site",
    },
    referrer: "https://www.dolarito.ar/",
    method: "GET",
    mode: "cors",
  });
  const data: DolaritoApiResponse = await response.json();
  return { buy: data.oficial.buy, sell: data.oficial.sell };
}

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

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

  if (!existingQuote) {
    await prisma.quote.create({
      data: {
        buy,
        sell,
        type: "BNA",
        difference: 0,
        percentage: 0,
        previousDayDifference: 0,
        previousDayPercentage: 0,
      },
    });
    await prisma.quoteHistory.create({
      data: { buy, sell, type: "BNA" },
    });
    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 BNA`);

  const todayStart = startOfToday();

  const prevDayHistory = await prisma.quoteHistory.findFirst({
    where: {
      type: "BNA",
      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: "BNA" },
  });
}
