import getConfig from 'next/config';
import jwt from 'jsonwebtoken';

// Password Validations 
import bcrypt from 'bcryptjs';

// Database 
import { db } from '@/helpers/api';

const { serverRuntimeConfig } = getConfig();

export const usersRepo = {
    authenticate,
    create,
};

async function authenticate({ email, password }) {
     const user = await db.User.scope('withHash').findOne({ where: { email } });

     if (!user) {
          throw 'Datele introduse nu sunt valide!';
     }
  
     let isPasswordValid = false;

     isPasswordValid = bcrypt.compareSync(password, user.hash);

     if (!isPasswordValid) {
          throw 'Datele introduse nu sunt valide!';
     }

     const token = jwt.sign({ sub: user.id }, serverRuntimeConfig.secret, { expiresIn: '14d' });

     const userJson = user.get();
     delete userJson.hash;

     return {
          token, 
     };
}

async function create(params) {
     if (await db.User.findOne({ where: { email: params.email } })) {
          throw 'Email-ul ' + params.email + ' este deja folosit !'; 
     }

     if(await db.User.findOne({ where: { userName: params.userName } })) {
          throw 'Numele de utilizator introdus este folosit de un alt utilizator.'; 
     }

     const user = new db.User(params);

     if (params.password) {
          user.hash = bcrypt.hashSync(params.password, 10);
     }

     await user.save();
}

