
import { isObject, isString } from '../../../../base/common/types.js';

function adaptManagedSettings(response, onWarn) {
    let extraKnownMarketplaces;
    if (isObject(response.extraKnownMarketplaces)) {
        const seen = ( new Set());
        const entries = [];
        for (const [name, entry] of Object.entries(response.extraKnownMarketplaces)) {
            if (!isObject(entry) || !isObject(entry.source)) {
                onWarn?.(
                    `[DefaultAccount] Skipping malformed extraKnownMarketplaces entry "${name}": expected { source: { source, repo|url } }`
                );
                continue;
            }
            const src = entry.source;
            let normalized;
            if (src.source === "github" && isString(src.repo)) {
                normalized = {
                    name,
                    source: {
                        source: "github",
                        repo: src.repo,
                        ...(src.ref ? {
                            ref: src.ref
                        } : {})
                    }
                };
            } else if (src.source === "git" && isString(src.url)) {
                normalized = {
                    name,
                    source: {
                        source: "git",
                        url: src.url,
                        ...(src.ref ? {
                            ref: src.ref
                        } : {})
                    }
                };
            } else if (src.source === "github" || src.source === "git") {
                onWarn?.(
                    `[DefaultAccount] Skipping extraKnownMarketplaces entry "${name}": source "${src.source}" requires ${src.source === "github" ? "\"repo\"" : "\"url\""}`
                );
            } else {
                onWarn?.(
                    `[DefaultAccount] Skipping extraKnownMarketplaces entry "${name}": unknown source type "${src.source}"`
                );
            }
            if (normalized && !( seen.has(name))) {
                seen.add(name);
                entries.push(normalized);
            }
        }
        extraKnownMarketplaces = entries;
    }
    return {
        enabledPlugins: isObject(response.enabledPlugins) ? response.enabledPlugins : undefined,
        extraKnownMarketplaces,
        strictKnownMarketplaces: typeof response.strictKnownMarketplaces === "boolean" ? response.strictKnownMarketplaces : undefined
    };
}

export { adaptManagedSettings };
