import { logger } from "../../utils/logger.js";
export class BaseFactory {
    items = new Map();
    aliasMap = new Map();
    initialized = false;
    initPromise = null;
    async ensureInitialized() {
        if (this.initialized) {
            return;
        }
        if (this.initPromise) {
            return this.initPromise;
        }
        this.initPromise = this.registerAll();
        await this.initPromise;
        this.initialized = true;
    }
    register(name, factory, aliases = [], metadata) {
        this.items.set(name, { factory, aliases, metadata });
        for (const alias of aliases) {
            this.aliasMap.set(alias.toLowerCase(), name);
        }
        logger.debug(`Registered ${name} with aliases: ${aliases.join(", ")}`);
    }
    async create(nameOrAlias, config) {
        await this.ensureInitialized();
        const name = this.resolveName(nameOrAlias);
        const registration = this.items.get(name);
        if (!registration) {
            throw new Error(`Unknown item: ${nameOrAlias}`);
        }
        return registration.factory(config);
    }
    resolveName(nameOrAlias) {
        const lower = nameOrAlias.toLowerCase();
        return this.aliasMap.get(lower) || nameOrAlias;
    }
    has(nameOrAlias) {
        const name = this.resolveName(nameOrAlias);
        return this.items.has(name);
    }
    getAvailable() {
        return Array.from(this.items.keys());
    }
    getAliases() {
        return new Map(this.aliasMap);
    }
    clear() {
        this.items.clear();
        this.aliasMap.clear();
        this.initialized = false;
        this.initPromise = null;
    }
}
