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 !'; 
     }

     const user = new db.User(params);

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

     user.firstName = params.firstName; 
     user.lastName = params.lastName; 

     await user.save();
}

