import { extractProviderId } from '../engine/provider-key/parse.js';
import { persistRoutingInstructionState } from '../engine/routing-state/store.js';
export function enforceAllowlistIntersection(engine, routingState, stateKey) {
    if (routingState.allowedProviders.size === 0) {
        return routingState;
    }
    const providersInRouting = new Set();
    for (const pools of Object.values(engine.routing)) {
        if (!Array.isArray(pools))
            continue;
        for (const pool of pools) {
            if (!pool || !Array.isArray(pool.targets))
                continue;
            for (const key of pool.targets) {
                if (typeof key !== 'string' || !key)
                    continue;
                const providerId = extractProviderId(key);
                if (providerId) {
                    providersInRouting.add(providerId);
                }
            }
        }
    }
    const allowed = Array.from(routingState.allowedProviders).filter((provider) => typeof provider === 'string');
    const hasIntersection = allowed.some((provider) => providersInRouting.has(provider));
    if (!hasIntersection) {
        const nextState = {
            ...routingState,
            allowedProviders: new Set()
        };
        engine.routingInstructionState.set(stateKey, nextState);
        persistRoutingInstructionState(stateKey, nextState, engine.routingStateStore);
        return nextState;
    }
    return routingState;
}
