import { ALL_AUTH_METHODS } from '../auth/types.js';
import { resolveConfig } from '../config/index.js';
import { findDwJson } from '../config/dw-json.js';
import { getLogger } from '../logging/logger.js';
export { ALL_AUTH_METHODS };
export { findDwJson };
/**
 * Extracts OAuth-related configuration from oclif flags.
 *
 * Use this to extract OAuth flags (--client-id, --client-secret, etc.)
 * from parsed oclif flags into a NormalizedConfig partial.
 *
 * @param flags - Parsed oclif flags
 * @returns Partial NormalizedConfig with OAuth fields
 *
 * @example
 * ```typescript
 * const flagConfig = extractOAuthFlags(this.flags);
 * return loadConfig(flagConfig, options);
 * ```
 */
export function extractOAuthFlags(flags) {
    const scopes = flags['auth-scope'];
    // Parse auth methods from --auth-methods or --user-auth flag
    const authMethodValues = flags['auth-methods'];
    let authMethods;
    if (flags['user-auth']) {
        authMethods = ['implicit'];
    }
    else if (authMethodValues && authMethodValues.length > 0) {
        const methods = authMethodValues
            .map((s) => s.trim())
            .filter((s) => ALL_AUTH_METHODS.includes(s));
        authMethods = methods.length > 0 ? methods : undefined;
    }
    return {
        clientId: flags['client-id'],
        clientSecret: flags['client-secret'],
        shortCode: flags['short-code'],
        tenantId: flags['tenant-id'],
        authMethods,
        accountManagerHost: flags['account-manager-host'],
        scopes: scopes && scopes.length > 0 ? scopes : undefined,
    };
}
/**
 * Extracts ODS-related configuration from oclif flags.
 *
 * Includes OAuth flags since ODS operations require OAuth authentication.
 *
 * @param flags - Parsed oclif flags
 * @returns Partial NormalizedConfig with ODS and OAuth fields
 */
export function extractOdsFlags(flags) {
    return {
        sandboxApiHost: flags['sandbox-api-host'],
        ...extractOAuthFlags(flags),
    };
}
/**
 * Extracts B2C instance-related configuration from oclif flags.
 *
 * Includes both instance-specific flags (--server, --username, etc.)
 * and OAuth flags since instance operations often need both.
 *
 * @param flags - Parsed oclif flags
 * @returns Partial NormalizedConfig with instance and OAuth fields
 *
 * @example
 * ```typescript
 * const flagConfig = extractInstanceFlags(this.flags);
 * return loadConfig(flagConfig, options);
 * ```
 */
export function extractInstanceFlags(flags) {
    return {
        // Instance-specific flags
        hostname: flags.server,
        webdavHostname: flags['webdav-server'],
        codeVersion: flags['code-version'],
        cipHost: flags['cip-host'],
        username: flags.username,
        password: flags.password,
        // TLS/mTLS options
        certificate: flags.certificate,
        certificatePassphrase: flags.passphrase,
        selfSigned: flags.selfsigned || !flags.verify,
        // Include OAuth flags (instance operations often need OAuth too)
        ...extractOAuthFlags(flags),
    };
}
/**
 * Extracts MRT (Managed Runtime) configuration from oclif flags.
 *
 * Use this to extract MRT flags (--api-key, --project, --environment, --cloud-origin, --credentials-file)
 * from parsed oclif flags. Returns both config values and loading options.
 *
 * @param flags - Parsed oclif flags
 * @returns Object with `config` (NormalizedConfig partial) and `options` (LoadConfigOptions partial)
 *
 * @example
 * ```typescript
 * const mrt = extractMrtFlags(this.flags);
 * const options: LoadConfigOptions = {
 *   ...this.getBaseConfigOptions(),
 *   ...mrt.options,
 * };
 * return loadConfig(mrt.config, options);
 * ```
 */
export function extractMrtFlags(flags) {
    const cloudOrigin = flags['cloud-origin'];
    const credentialsFile = flags['credentials-file'];
    return {
        config: {
            mrtApiKey: flags['api-key'],
            mrtProject: flags.project,
            mrtEnvironment: flags.environment,
            mrtOrigin: cloudOrigin,
        },
        options: {
            cloudOrigin,
            credentialsFile,
        },
    };
}
/**
 * Loads configuration with precedence: CLI flags/env vars > dw.json > ~/.mobify
 *
 * OCLIF handles environment variables automatically via flag `env` properties.
 * The flags parameter already contains resolved env var values.
 *
 * Uses {@link resolveConfig} internally for consistent behavior across CLI and SDK.
 *
 * @param flags - Configuration values from CLI flags/env vars
 * @param options - Loading options
 * @param pluginSources - @deprecated Plugin sources are now registered globally via
 *   {@link globalConfigSourceRegistry}. This parameter is retained for backwards compatibility.
 * @returns Resolved configuration with factory methods
 *
 * @example
 * ```typescript
 * // In a CLI command
 * const config = loadConfig(
 *   { hostname: this.flags.server, clientId: this.flags['client-id'] },
 *   { instance: this.flags.instance }
 * );
 *
 * if (config.hasB2CInstanceConfig()) {
 *   const instance = config.createB2CInstance();
 * }
 * ```
 */
export async function loadConfig(flags = {}, options = {}, pluginSources = {}) {
    const logger = getLogger();
    // Preserve instanceName and projectDirectory from options if not already in flags
    const effectiveFlags = {
        ...flags,
        instanceName: flags.instanceName ?? options.instance,
        projectDirectory: flags.projectDirectory ?? options.projectDirectory,
        workingDirectory: flags.workingDirectory ?? options.workingDirectory,
    };
    const resolved = await resolveConfig(effectiveFlags, {
        instance: options.instance,
        configPath: options.configPath,
        projectDirectory: options.projectDirectory,
        workingDirectory: options.workingDirectory,
        hostnameProtection: true,
        cloudOrigin: options.cloudOrigin,
        credentialsFile: options.credentialsFile,
        accountManagerHost: options.accountManagerHost,
        sourcesBefore: pluginSources.before,
        sourcesAfter: pluginSources.after,
    });
    // Log warnings (at warn level so users can see configuration issues)
    for (const warning of resolved.warnings) {
        logger.warn({ warning }, `[Config] ${warning.message}`);
    }
    return resolved;
}
//# sourceMappingURL=config.js.map