"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("reflect-metadata");
const core_1 = require("@nestjs/core");
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const bcrypt = require("bcrypt");
const readline = require("readline");
const app_module_1 = require("../app.module");
const user_entity_1 = require("../appapi/user/user.entity");
function generateUserId(name, email) {
    const timestamp = Date.now();
    const emailInitials = email.slice(0, 2).toUpperCase();
    const year = new Date().getFullYear();
    return `${name.replace(/\s+/g, '').toLowerCase()}${emailInitials}${year}${timestamp}`;
}
function prompt(rl, question) {
    return new Promise((resolve) => rl.question(question, resolve));
}
async function bootstrap() {
    const logger = new common_1.Logger('CreateAdminUser');
    const [, , argName, argEmail, argMobile, argPassword] = process.argv;
    let name = argName;
    let email = argEmail;
    let mobile = argMobile;
    let password = argPassword;
    if (!name || !email || !mobile || !password) {
        const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
        logger.log('Enter admin user details (or pass as CLI args: name email mobile password)');
        name = name || (await prompt(rl, 'Name: ')).trim();
        email = email || (await prompt(rl, 'Email: ')).trim();
        mobile = mobile || (await prompt(rl, 'Mobile number (e.g. +971501234567): ')).trim();
        password = password || (await prompt(rl, 'Password: ')).trim();
        rl.close();
    }
    if (!name || !email || !mobile || !password) {
        logger.error('All fields (name, email, mobile, password) are required.');
        process.exit(1);
    }
    const app = await core_1.NestFactory.createApplicationContext(app_module_1.AppModule, {
        logger: ['error', 'warn'],
    });
    try {
        const userRepository = app.get((0, typeorm_1.getRepositoryToken)(user_entity_1.User));
        const existingByEmail = await userRepository.findOne({ where: { email } });
        if (existingByEmail) {
            logger.error(`A user with email "${email}" already exists.`);
            process.exit(1);
        }
        const existingByMobile = await userRepository.findOne({ where: { mobileNumber: mobile } });
        if (existingByMobile) {
            logger.error(`A user with mobile "${mobile}" already exists.`);
            process.exit(1);
        }
        const hashedPassword = await bcrypt.hash(password, await bcrypt.genSalt());
        const userId = generateUserId(name, email);
        const admin = userRepository.create({
            userId,
            name,
            email,
            mobileNumber: mobile,
            password: hashedPassword,
            roles: [user_entity_1.UserRole.ADMIN],
            userVerified: true,
            status: 'active',
        });
        await userRepository.save(admin);
        logger.log(`Admin user created successfully.`);
        logger.log(`  Name:   ${admin.name}`);
        logger.log(`  Email:  ${admin.email}`);
        logger.log(`  Mobile: ${admin.mobileNumber}`);
        logger.log(`  userId: ${admin.userId}`);
    }
    finally {
        await app.close();
    }
}
bootstrap().catch((error) => {
    const logger = new common_1.Logger('CreateAdminUser');
    logger.error(error?.message || 'Failed to create admin user.', error?.stack);
    process.exit(1);
});
//# sourceMappingURL=create-admin-user.js.map