import { UIEventScope } from '@devvit/protos';
import { Header } from '@devvit/shared-types/Header.js';
import { EffectHandler } from './effect-handler.js';
/**
 * Handles parsing app effects to handle CreateOrder effects
 */
export class CreateOrderEffectHandler extends EffectHandler {
    constructor() {
        super(...arguments);
        // subclasses can adjust this if needed so we don't need to rebuild ui-renderer if requirements change
        this.metadataKeys = [Header.App, Header.AppUser, Header.Version];
    }
    onEvent(ev) {
        const { createOrder: order } = ev.detail.effect;
        if (!order)
            return;
        if (order.skus.length === 0) {
            console.warn(`[handler] missing products`);
            return;
        }
        const orderMetadata = order.metadata || {};
        const installId = ev.detail.metadata?.[Header.Installation]?.values?.[0];
        if (!installId) {
            console.warn(`[handler] missing installation ID`);
            return;
        }
        orderMetadata[Header.Installation] = installId;
        if (devvit?.debug.payments) {
            const skuStr = JSON.stringify(order.skus);
            const metaStr = JSON.stringify(order.metadata);
            console.debug(`[handler] launching order flow for: ${skuStr} (metadata: ${metaStr})`);
        }
        const callMetadata = {};
        // only pass the relevant metadata to the onOrder handler
        this.metadataKeys.forEach((entry) => {
            const value = ev.detail.metadata?.[entry]?.values?.[0];
            if (value) {
                callMetadata[entry] = value;
            }
        });
        this.onOrder(order.skus, orderMetadata, callMetadata, (status, orderId, errorCode, errorMessage) => {
            ev.detail.onEvent({
                scope: UIEventScope.ALL,
                orderResult: {
                    status,
                    orderId,
                    errorCode,
                    errorMessage,
                    order,
                },
                hook: order.id,
            });
        });
    }
}
//# sourceMappingURL=create-order-effect-handler.js.map