import { BaseAuthProvider } from './BaseAuthProvider.js';
import { MJGlobal } from '@memberjunction/global';
import './providers/Auth0Provider.js';
import './providers/MSALProvider.js';
import './providers/OktaProvider.js';
import './providers/CognitoProvider.js';
import './providers/GoogleProvider.js';
export class AuthProviderFactory {
    static instance;
    providers = new Map();
    issuerCache = new Map();
    constructor() { }
    static getInstance() {
        if (!AuthProviderFactory.instance) {
            AuthProviderFactory.instance = new AuthProviderFactory();
        }
        return AuthProviderFactory.instance;
    }
    static createProvider(config) {
        try {
            const provider = MJGlobal.Instance.ClassFactory.CreateInstance(BaseAuthProvider, config.type.toLowerCase(), config);
            if (!provider) {
                throw new Error(`No provider registered for type: ${config.type}`);
            }
            return provider;
        }
        catch (error) {
            const message = error instanceof Error ? error.message : String(error);
            throw new Error(`Failed to create authentication provider for type '${config.type}': ${message}`);
        }
    }
    register(provider) {
        if (!provider.validateConfig()) {
            throw new Error(`Invalid configuration for provider: ${provider.name}`);
        }
        this.providers.set(provider.name, provider);
        this.issuerCache.clear();
        console.log(`Registered auth provider: ${provider.name} with issuer: ${provider.issuer}`);
    }
    getByIssuer(issuer) {
        if (this.issuerCache.has(issuer)) {
            return this.issuerCache.get(issuer);
        }
        for (const provider of this.providers.values()) {
            if (provider.matchesIssuer(issuer)) {
                this.issuerCache.set(issuer, provider);
                return provider;
            }
        }
        return undefined;
    }
    getByName(name) {
        return this.providers.get(name);
    }
    getAllProviders() {
        return Array.from(this.providers.values());
    }
    hasProviders() {
        return this.providers.size > 0;
    }
    clear() {
        this.providers.clear();
        this.issuerCache.clear();
    }
    static getRegisteredProviderTypes() {
        const registrations = MJGlobal.Instance.ClassFactory.GetAllRegistrations(BaseAuthProvider);
        const providerTypes = registrations
            .map(reg => reg.Key)
            .filter((key) => key !== null && key !== undefined);
        return Array.from(new Set(providerTypes));
    }
    static isProviderTypeRegistered(type) {
        try {
            const registration = MJGlobal.Instance.ClassFactory.GetRegistration(BaseAuthProvider, type.toLowerCase());
            return registration !== null && registration !== undefined;
        }
        catch {
            return false;
        }
    }
}
//# sourceMappingURL=AuthProviderFactory.js.map