import { format } from "date-fns" type HistoricRate = { currency: string rate: number inverse: number } export async function getCurrencyRate(currencyCodeFrom: string, currencyCodeTo: string, date: Date): Promise { const rates = await fetchHistoricalCurrencyRates(currencyCodeFrom, date) if (!rates || rates.length === 0) { console.log("Could not fetch currency rates", currencyCodeFrom, currencyCodeTo, date) return 0 } const rate = rates.find((rate) => rate.currency === currencyCodeTo) if (!rate) { console.log("Could not find currency rate", currencyCodeFrom, currencyCodeTo, date) return 0 } return rate.rate } export async function fetchHistoricalCurrencyRates(currency: string = "USD", date: Date): Promise { const formattedDate = format(date, "yyyy-MM-dd") const url = `https://corsproxy.io/?${encodeURIComponent( `https://www.xe.com/currencytables/?from=${currency}&date=${formattedDate}` )}` const response = await fetch(url) if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`) } const html = await response.text() // Extract the JSON data from the __NEXT_DATA__ script tag const scriptTagRegex = /