import {cryptoUtil} from '../util/cryptoUtil.js';
import {config} from '../config.js';
import {dbService} from './dbService.js';

class UserService {
    login(username, password) {
        return new Promise(function (resolve, reject) {
            const selectUser = 'SELECT * FROM users WHERE username=$1';
            if (username && password) {
                dbService.client.query(selectUser, [username])
                    .then(async function (userObject) {
                        if (userObject.rows[0] && userObject.rows[0].password === cryptoUtil.hashPwd(password)) {
                            let {id, username, firstname, lastname, email} = userObject.rows[0];
                            const owner = {id, username, firstname, lastname, email};
                            const token = await cryptoUtil.createToken(owner, config.jwt.jwtSecret, config.jwt.signOptions);
                            resolve({token, owner});
                        } else {
                            resolve(false);
                        }
                    });
            }
        });
    }

    register(username, firstname, lastname, email, password) {
        return new Promise(function (resolve, reject) {
            const createUser = 'INSERT INTO users(username, firstname, lastname, email, password) VALUES($1,$2,$3,$4,$5)';
            const createUserValues = [username, firstname, lastname, email, cryptoUtil.hashPwd(password)];
            if (username && email && password) {
                dbService.client.query(createUser, createUserValues)
                    .then(res => {
                        resolve(true);
                    })
                    .catch(err => {
                        console.log(err.stack);
                        resolve(false);
                    });
            }
        });
    }

}
export const userService = new UserService();