import crypto from 'crypto';

export default class PasswordMgmt {
    static async generatePasswordHash(password: string): Promise<string> {
        return new Promise((resolve, reject) => {
            const salt = crypto.randomBytes(16).toString('hex');

            crypto.scrypt(password, salt, 64, (err, derivedKey) => {
                if (err) reject(err);
                resolve(`${salt}:${derivedKey.toString('hex')}`);
            });
        });
    }

    static async verifyPassword(
        password: string,
        hash: string
    ): Promise<boolean> {
        return new Promise((resolve, reject) => {
            const [salt, key] = hash.split(':');
            crypto.scrypt(password, salt, 64, (err, derivedKey) => {
                if (err) reject(err);
                resolve(key === derivedKey.toString('hex'));
            });
        });
    }

    static generatePassword(length: number = 64): string {
        return crypto.randomBytes(length).toString('hex');
    }
}
