"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generatePlugins = void 0;
const mapping_kit_1 = require("@segment/actions-core/mapping-kit");
const destination_subscriptions_1 = require("@segment/destination-subscriptions");
const load_script_1 = require("./load-script");
const resolve_when_1 = require("./resolve-when");
function generatePlugins(def, settings, subscriptions) {
    let hasInitialized = false;
    let client;
    let analytics;
    let initializing;
    const load = async (_ctx, analyticsInstance) => {
        if (hasInitialized) {
            return;
        }
        if (initializing) {
            await initializing;
            return;
        }
        analytics = analyticsInstance;
        initializing = def.initialize?.({ settings, analytics }, { loadScript: load_script_1.loadScript, resolveWhen: resolve_when_1.resolveWhen });
        client = await initializing;
        hasInitialized = true;
    };
    return Object.entries(def.actions).reduce((acc, [key, action]) => {
        const actionSubscriptions = subscriptions.filter((s) => s.enabled && s.partnerAction === key);
        if (actionSubscriptions.length === 0)
            return acc;
        async function evaluate(ctx) {
            const invocations = [];
            for (const sub of actionSubscriptions) {
                const isSubscribed = destination_subscriptions_1.validate(destination_subscriptions_1.parseFql(sub.subscribe), ctx.event);
                if (!isSubscribed)
                    continue;
                const mapping = (sub.mapping ?? {});
                const payload = mapping_kit_1.transform(mapping, ctx.event);
                const input = {
                    payload,
                    mapping,
                    settings,
                    analytics,
                    context: ctx
                };
                invocations.push(action.perform(client, input));
            }
            await Promise.all(invocations);
            return ctx;
        }
        const plugin = {
            name: `${def.name} ${key}`,
            type: action.lifecycleHook ?? 'destination',
            version: '0.1.0',
            ready: () => Promise.resolve(),
            isLoaded: () => hasInitialized,
            load,
            track: evaluate,
            page: evaluate,
            alias: evaluate,
            identify: evaluate,
            group: evaluate
        };
        acc.push(plugin);
        return acc;
    }, []);
}
exports.generatePlugins = generatePlugins;
//# sourceMappingURL=plugin.js.map