#!/usr/bin/env node

const bcrypt = require('bcryptjs');
const dbManager = require('../database/DatabaseManager');
const AdminUserRepository = require('../repositories/AdminUserRepository');

const DEFAULT_SALT_ROUNDS = parseInt(process.env.ADMIN_PASSWORD_SALT_ROUNDS || '12', 10);

const printUsage = () => {
    console.log('Usage: node src/scripts/createAdminUser.js --username <name> --password <pass> [--role <role>] [--require-password-change]');
    console.log('Example: npm run create-admin -- --username admin2 --password "SehrSicher123!"');
};

const parseArgs = () => {
    const rawArgs = process.argv.slice(2);
    const args = {};

    for (let i = 0; i < rawArgs.length; i++) {
        const arg = rawArgs[i];
        if (!arg.startsWith('--')) {
            continue;
        }

        const key = arg.slice(2);
        const next = rawArgs[i + 1];
        if (!next || next.startsWith('--')) {
            args[key] = true;
        } else {
            args[key] = next;
            i++;
        }
    }

    return args;
};

const validateInput = ({ username, password }) => {
    if (!username || !username.trim()) {
        throw new Error('USERNAME_REQUIRED');
    }

    if (!password || password.length < 10) {
        throw new Error('PASSWORD_TOO_WEAK');
    }
};

(async () => {
    const args = parseArgs();

    if (args.help || args.h) {
        printUsage();
        process.exit(0);
    }

    try {
        validateInput(args);
    } catch (validationError) {
        console.error('⚠️  Validation error:', validationError.message);
        printUsage();
        process.exit(1);
    }

    const normalizedUsername = args.username.trim().toLowerCase();
    const role = args.role || 'admin';
    const requirePasswordChange = Boolean(args['require-password-change']);

    // Skip expensive preview generation for CLI usage
    process.env.SKIP_PREVIEW_GENERATION = process.env.SKIP_PREVIEW_GENERATION || '1';

    try {
        await dbManager.initialize();

        const existingUser = await AdminUserRepository.getByUsername(normalizedUsername);
        if (existingUser) {
            console.error(`❌ Benutzer '${normalizedUsername}' existiert bereits.`);
            process.exit(1);
        }

        const passwordHash = await bcrypt.hash(args.password, DEFAULT_SALT_ROUNDS);
        const id = await AdminUserRepository.createAdminUser({
            username: normalizedUsername,
            passwordHash,
            role,
            requiresPasswordChange: requirePasswordChange
        });

        console.log('✅ Admin-Benutzer angelegt:');
        console.log(`   ID: ${id}`);
        console.log(`   Username: ${normalizedUsername}`);
        console.log(`   Rolle: ${role}`);
        console.log(`   Passwort-Änderung erforderlich: ${requirePasswordChange}`);
    } catch (error) {
        console.error('❌ Fehler beim Anlegen des Admin-Benutzers:', error.message);
        process.exit(1);
    } finally {
        try {
            await dbManager.close();
        } catch (closeError) {
            console.warn('⚠️  Datenbank konnte nicht sauber geschlossen werden:', closeError.message);
        }
    }
})();
