import { PRODUCT_ID } from "../../src/config/stripe";
import { fetchPrices } from "../_stripe";

const PricesToCountry: any = {
  JP: "JPY",
  UK: "GBP",
  GB: "GBP",
  US: "USD",
  AU: "AUD",
  RU: "RUB",
};

// see: https://stripe.com/docs/currencies#zero-decimal
const zeroDecimalCurrencies = [
  "BIF",
  "CLP",
  "DJF",
  "GNF",
  "JPY",
  "KMF",
  "KRW",
  "MGA",
  "PYG",
  "RWF",
  "UGX",
  "VND",
  "VUV",
  "XAF",
  "XOF",
  "XPF",
];

const getCurrencyForCountry = (country: string) => {
  console.log("🚀️ ~ country", country);

  return PricesToCountry[country] || "EUR";
};

export const onRequest: PagesFunction<PagesEnv> = async ({ request, env }) => {
  const response = await fetchPrices(
    {
      product: env.STRIPE_PRODUCT_ID ? env.STRIPE_PRODUCT_ID : PRODUCT_ID,
      active: true,
      // @ts-ignore
      currency: getCurrencyForCountry(request.cf.country),
    },
    env.STRIPE_SECRET_KEY
  ).then((res) =>
    res.data
      .map((price) => ({
        id: price.id,
        name: price.nickname,
        price:
          (price.unit_amount || 0) /
          (zeroDecimalCurrencies.includes(price.currency.toUpperCase())
            ? 1
            : 100),
        currency: price.currency,
        // recurring: {
        //   interval: price.recurring?.interval,
        //   interval_count: price.recurring?.interval_count,
        // },
      }))
      .sort(({ price: aPrice }, { price: bPrice }) => -bPrice + aPrice)
  );

  return new Response(JSON.stringify(response));
};
