const User = require("../../models/user");
const bcryptjs = require("bcryptjs");
const JWT = require("jsonwebtoken");
const config = require("../../config");
const Beautician = require("../../models/beautician")

exports.getUserById = async (req, res) => {
  console.log("here");
  try {
    console.log("req.param", req.param);
    const userId = req.params.id;
    const user = await User.findOne({
      where: { id: userId }
    });
    res.status(200).send(user);
  } catch (err) {
    console.log(err);
    res.sendStatus(401);
  }
};
createToken = id => {
  return JWT.sign({ id }, config.JWT_SECRET);
};

exports.register = async (req, res) => {
  try {
    const registerData = req.body;
 
    const user = await User.findOne({
      where: { email: registerData.email }
    });

    if (user) {
      return res.status(400).json({ message: "อีเมลนี้ถูกใช้งานแล้ว" });
    } else {
      const passwordHash = await bcryptjs.hash(registerData.password, 10);
      const newUser = await User.create({
        name: registerData.name,
        email: registerData.email,
        password: passwordHash,
        address: registerData.address,
        tel: registerData.tel,
        role: registerData.role
      });
     
      const token = await createToken(newUser.id);
      res.status(200).send("success");
    }
  } catch (err) {
    console.log(err);
    res.sendStatus(401);
  }
};

exports.login = async (req, res) => {
  const loginData = req.body;
  const user = await User.findOne({
    where: { email: loginData.email }
  });
  if (!user) {
    return res.status(400).json({ message: "email หรือ รหัสผ่านไม่ถูกต้อง" });
  } else {
    const chkPassword = await bcryptjs.compare(
      loginData.password,
      user.dataValues.password
    );
    if (chkPassword === false) {
      return res.status(400).json({ message: "รหัสผ่านไม่ถูกต้อง" });
    }
    const token = await createToken(user.dataValues.id);
    res.status(200).send({token});
  }
};

exports.currentUser = async (req, res) => {
  const token = req.headers.token;
  const decode = await JWT.verify(token, config.JWT_SECRET);
  const user = await User.findOne({
    where: {
      id: decode.id
    }
  });
  res.status(200).send(user);
};
