import { isCrawler } from "../utils/isCrawler.js";
import { promiseTimeout } from "../utils/promiseTimeout.js";

import type { PreDecisionGateway, PreDecisionGatewayResult } from "./gateway.js";

/**
 * Dynamically allow to get a predecision with a extra request to an external API.
 * If your server does not respond within a given timeout or with an error, it automatically
 * continues with the predecisions. Otherwise, the predecision of the response is used.
 */
const preDecisionGatewayDynamicRequest: (
    request: () => Promise<{
        predecision: false | PreDecisionGatewayResult;
    }>,
    timeout?: number,
    active?: boolean,
) => PreDecisionGateway =
    (request, timeout = 10000, active = true) =>
    async ({ getUserDecision }) => {
        if (isCrawler() || !active) {
            // Ignore unnecessary requests
            return false;
        }

        // Check if revision has changed, and probably access our dynamic predecision again
        const decision = getUserDecision();
        if (decision) {
            return "consent";
        }

        try {
            const { predecision } = await promiseTimeout(request(), timeout);
            return predecision;
        } catch (e) {
            return false;
        }
    };

export { preDecisionGatewayDynamicRequest };
