import { regExpPatternFromWildcardName } from "../utils/regExpPatternFromWildcardName.js";

type BlockerDefinition = { id: string | number; services: number[]; rules: string[] };

/**
 * Synchronously check if a content is blocked and returns the found content blocker.
 * See `window.consentApi.unblock` for more documentation.
 */
function unblockSync(
    blocker: Array<BlockerDefinition>,
    url: string,
    options?: {
        /**
         * Allows to map the rules of the content blocker which are considered for the check if the URL is blocked.
         * Return a falsy value to skip the rule.
         */
        mapRule?: (rule: string) => string;
    },
) {
    const { mapRule } = options || {};
    if (!url) {
        return undefined;
    }

    // Find matching blocker
    let found: BlockerDefinition;

    loop1: for (const row of blocker) {
        const { rules } = row;
        // Check if host matches
        for (const rule of rules) {
            const useRule = mapRule ? mapRule(rule) : rule;

            if (!useRule) {
                continue;
            }

            const regexp = regExpPatternFromWildcardName(useRule);
            if (url.match(new RegExp(regexp, "s"))) {
                found = row;
                break loop1;
            }
        }
    }

    return found;
}

export { unblockSync };
