const bcrypt = require('bcrypt');
const sequelize = require('../config/db.js');
const models = require('../models/index.js');

const SALT_ROUNDS = 10;

const parseArgs = (argv) => {
    const args = {};
    for (let i = 2; i < argv.length; i += 1) {
        const arg = argv[i];
        if (!arg.startsWith('--')) continue;
        const key = arg.slice(2);
        const value = argv[i + 1];
        if (!value || value.startsWith('--')) {
            args[key] = true;
            continue;
        }
        args[key] = value;
        i += 1;
    }
    return args;
};

const printHelp = () => {
    console.log('Reset the password of an admin (active) user from CLI');
    console.log('');
    console.log('Usage:');
    console.log('  npm run reset:admin-password -- --username <username> --password <newPassword>');
    console.log('');
    console.log('Options:');
    console.log('  --username   Username of the target admin user (required)');
    console.log('  --password   New plaintext password (required, min 8 chars)');
    console.log('  --help       Show this help text');
};

const main = async () => {
    const args = parseArgs(process.argv);

    if (args.help) {
        printHelp();
        return;
    }

    const hasUsername = typeof args.username === 'string' && args.username.trim().length > 0;
    const hasPassword = typeof args.password === 'string' && args.password.length > 0;

    if (!hasUsername || !hasPassword) {
        printHelp();
        process.exitCode = 1;
        return;
    }

    if (args.password.length < 8) {
        console.error('Password must be at least 8 characters.');
        process.exitCode = 1;
        return;
    }

    const username = args.username.trim().toLowerCase();

    const user = await models.User.findOne({
        where: { username, status: 'active' },
        attributes: ['id', 'username', 'status']
    });

    if (!user) {
        console.error(`No active user found with username "${username}".`);
        process.exitCode = 1;
        return;
    }

    const hashedPassword = await bcrypt.hash(args.password, SALT_ROUNDS);

    await models.User.update(
        { password: hashedPassword },
        { where: { id: user.id } }
    );

    console.log(`Password reset for admin user "${user.username}" (id: ${user.id}).`);
};

main()
    .catch((err) => {
        const msg = err?.message || String(err);
        if (msg.includes("Data too long for column 'password'")) {
            console.error('Password reset failed: users.password column is too short for bcrypt hash.');
            console.error('Run this once on DB: ALTER TABLE users MODIFY password VARCHAR(250) NOT NULL;');
        } else {
            console.error('Password reset failed:', msg);
        }
        process.exitCode = 1;
    })
    .finally(async () => {
        try {
            await sequelize.close();
        } catch (_) {
            // Best effort close only.
        }
    });
