import { PREDECISION_GATEWAY_EVENT_PROMISES } from "../events/predecisionEventPromises.js";

import type { PreDecisionGateway } from "./gateway.js";
import type { PreDecisionGatewayEventPromises } from "../events/predecisionEventPromises.js";

/**
 * See `PreDecisionGatewayEventPromises` for documentation.
 */
const preDecisionGatewayEventPromises: PreDecisionGateway = async () => {
    const promises: PreDecisionGatewayEventPromises["promises"] = [];
    document.dispatchEvent(
        new CustomEvent<PreDecisionGatewayEventPromises>(PREDECISION_GATEWAY_EVENT_PROMISES, {
            detail: {
                promises,
            },
        }),
    );

    try {
        const results = await Promise.all(promises);

        for (const result of results) {
            if (result) {
                return result;
            }
        }
    } catch (e) {
        // Silence is golden.
    }

    return false;
};

export { preDecisionGatewayEventPromises };
