"use strict";
/**
 * Config Auth Setup Command
 *
 * Interactive wizard for configuring dashboard authentication.
 * Prompts for username and password, hashes password with bcrypt,
 * and saves to config.yaml.
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleSetup = void 0;
const bcrypt_1 = __importDefault(require("bcrypt"));
const prompt_1 = require("../../utils/prompt");
const ui_1 = require("../../utils/ui");
const config_loader_facade_1 = require("../../config/config-loader-facade");
const BCRYPT_ROUNDS = 10;
const MIN_PASSWORD_LENGTH = 8;
/**
 * Validate username (non-empty, alphanumeric with underscores)
 */
function validateUsername(value) {
    if (!value || value.trim().length === 0) {
        return 'Username cannot be empty';
    }
    if (!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(value)) {
        return 'Username must start with letter, contain only letters/numbers/underscores/hyphens';
    }
    if (value.length < 3) {
        return 'Username must be at least 3 characters';
    }
    return null;
}
/**
 * Handle setup command - interactive wizard
 */
async function handleSetup() {
    await (0, ui_1.initUI)();
    console.log('');
    console.log((0, ui_1.header)('Dashboard Auth Setup'));
    console.log('');
    console.log((0, ui_1.info)('Configure username and password for dashboard access.'));
    console.log((0, ui_1.dim)('    Password will be hashed with bcrypt before storage.'));
    console.log('');
    // Check for ENV overrides
    if (process.env.CCS_DASHBOARD_AUTH_ENABLED ||
        process.env.CCS_DASHBOARD_USERNAME ||
        process.env.CCS_DASHBOARD_PASSWORD_HASH) {
        console.log((0, ui_1.warn)('Environment variables detected - they will override config values:'));
        if (process.env.CCS_DASHBOARD_AUTH_ENABLED) {
            console.log(`    CCS_DASHBOARD_AUTH_ENABLED=${process.env.CCS_DASHBOARD_AUTH_ENABLED}`);
        }
        if (process.env.CCS_DASHBOARD_USERNAME) {
            console.log(`    CCS_DASHBOARD_USERNAME=${process.env.CCS_DASHBOARD_USERNAME}`);
        }
        if (process.env.CCS_DASHBOARD_PASSWORD_HASH) {
            console.log('    CCS_DASHBOARD_PASSWORD_HASH=***');
        }
        console.log('');
    }
    try {
        // Prompt for username
        console.log((0, ui_1.subheader)('Username'));
        const username = await prompt_1.InteractivePrompt.input('Enter username', {
            validate: validateUsername,
        });
        console.log('');
        // Prompt for password
        console.log((0, ui_1.subheader)('Password'));
        console.log((0, ui_1.dim)(`    Minimum ${MIN_PASSWORD_LENGTH} characters`));
        const password = await prompt_1.InteractivePrompt.password('Enter password');
        // Validate password length
        if (password.length < MIN_PASSWORD_LENGTH) {
            console.log('');
            console.log((0, ui_1.fail)(`Password must be at least ${MIN_PASSWORD_LENGTH} characters`));
            return { success: false, error: 'Password too short' };
        }
        // Confirm password
        const confirmPassword = await prompt_1.InteractivePrompt.password('Confirm password');
        if (password !== confirmPassword) {
            console.log('');
            console.log((0, ui_1.fail)('Passwords do not match'));
            return { success: false, error: 'Password mismatch' };
        }
        console.log('');
        console.log((0, ui_1.info)('Hashing password...'));
        // Hash password
        const passwordHash = await bcrypt_1.default.hash(password, BCRYPT_ROUNDS);
        const config = (0, config_loader_facade_1.mutateConfig)((currentConfig) => {
            currentConfig.dashboard_auth = {
                enabled: true,
                username,
                password_hash: passwordHash,
                session_timeout_hours: currentConfig.dashboard_auth?.session_timeout_hours ?? 24,
            };
        });
        console.log('');
        console.log((0, ui_1.ok)('Dashboard authentication configured'));
        console.log('');
        console.log((0, ui_1.info)('Settings saved to ~/.ccs/config.yaml'));
        console.log((0, ui_1.info)(`Username: ${username}`));
        console.log((0, ui_1.info)(`Session timeout: ${config.dashboard_auth?.session_timeout_hours ?? 24} hours`));
        console.log('');
        console.log((0, ui_1.dim)('    Start dashboard: ccs config'));
        console.log((0, ui_1.dim)('    Show status: ccs config auth show'));
        console.log((0, ui_1.dim)('    Disable auth: ccs config auth disable'));
        console.log('');
        return { success: true, username };
    }
    catch (error) {
        const err = error;
        console.log('');
        console.log((0, ui_1.fail)(`Setup failed: ${err.message}`));
        return { success: false, error: err.message };
    }
}
exports.handleSetup = handleSetup;
//# sourceMappingURL=setup-command.js.map