const member = require("../../models").member;

const jwt = require('jsonwebtoken');
var bcrypt = require('bcrypt');

module.exports = {
  async create(req) {
    console.log(req.body)
    const { username, password, firstname, lastname, phone, email } = req.body;
    const user = {
      username: username,
      password: password,
      firstname: firstname,
      lastname: lastname,
      phone: phone,
      email: email
    }
    return await member.create(user);
  },
  async login(req) {
    try {
      const user = await member.findOne({
        where: { username: req.body.username }
      });
      if (user) {
        const cmp = await bcrypt.compare(req.body.password, user.password);

        if (cmp) {
          user.last_login = Date.now()
          user.save()
          console.log(user)
          const token = jwt.sign({
            username: user.username
          },
            process.env.TOKEN_SECRET, { expiresIn: process.env.TOKEN_EXPIRES }
          );
          console.log(token)
          return {
            accessToken: token
          };
        } else {
          return "Wrong username or password.";
        }
      } else {
        return "Wrong username or password.";
      }
    } catch (error) {
      return "Internal Server error Occured";
    }
  },
  async getProfile(req) {
    const username = req.user.username;
    return await member.findOne({
      where: { username: username },
      attributes: ['username', 'email', 'phone', 'firstname', 'lastname']
    });
  }


}