"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSKUForPaddleId = exports.getPlanByCode = exports.loadPlanPricesUntilSuccess = exports.SubscriptionPlans = void 0;
const _ = require("lodash");
const util_1 = require("@httptoolkit/util");
const util_2 = require("./util");
exports.SubscriptionPlans = {
    'pro-monthly': { paddleId: 550380, name: 'Pro (monthly)' },
    'pro-annual': { paddleId: 550382, name: 'Pro (annual)' },
    'team-monthly': { paddleId: 550789, name: 'Team (monthly)' },
    'team-annual': { paddleId: 550788, name: 'Team (annual)' },
    // Defunct, but kept to support existing accounts:
    'pro-perpetual': { paddleId: 599788, name: 'Pro (perpetual)', prices: 'priceless' }
};
async function loadPlanPrices() {
    const response = await fetch(`${util_2.ACCOUNTS_API_BASE}/get-prices`);
    if (!response.ok) {
        console.log(response);
        throw new Error(`Failed to look up prices, got ${response.status}: ${response.statusText}`);
    }
    const data = await response.json();
    if (!data.success) {
        console.log(data);
        throw new Error("Price lookup request was unsuccessful");
    }
    const productPrices = data.response.products;
    productPrices.forEach((productPrice) => {
        const plan = _.find(exports.SubscriptionPlans, { paddleId: productPrice.product_id });
        if (!plan)
            return;
        const currency = productPrice.currency;
        const totalPrice = productPrice.price.net;
        const monthlyPrice = productPrice.subscription.interval === 'year'
            ? totalPrice / 12
            : totalPrice;
        plan.prices = {
            rawTotal: totalPrice,
            currency: currency,
            total: formatPrice(currency, totalPrice),
            monthly: formatPrice(currency, monthlyPrice)
        };
    });
    return exports.SubscriptionPlans;
}
async function loadPlanPricesUntilSuccess() {
    // Async load all plan prices, repeatedly, until it works
    await (0, util_1.doWhile)(
    // Do: load the prices, with a timeout
    () => Promise.race([
        loadPlanPrices().catch(console.warn),
        (0, util_1.delay)(5000) // 5s timeout
    ]).then(() => (0, util_1.delay)(1000)), // Limit the frequency
    // While: if any subs didn't successfully get data, try again:
    () => _.some(exports.SubscriptionPlans, (plan) => !plan.prices));
    return exports.SubscriptionPlans;
}
exports.loadPlanPricesUntilSuccess = loadPlanPricesUntilSuccess;
function formatPrice(currency, price) {
    return Number(price).toLocaleString(undefined, {
        style: "currency",
        currency: currency,
        minimumFractionDigits: _.round(price) === price ? 0 : 2,
        maximumFractionDigits: 2
    });
}
const getPlanByCode = (sku) => exports.SubscriptionPlans[sku];
exports.getPlanByCode = getPlanByCode;
const getSKUForPaddleId = (paddleId) => _.findKey(exports.SubscriptionPlans, { paddleId: paddleId });
exports.getSKUForPaddleId = getSKUForPaddleId;
//# sourceMappingURL=plans.js.map