var Sequelize = require('sequelize');
const nodemailer = require('nodemailer');
const { body, validationResult } = require('express-validator');

const member = require("../models").member;
const memberServices = require("../services").members;
module.exports = {
  validate(method) {
    switch (method) {
      case 'createUser':
        {
          return [
            body('username', 'userName doesn\'t exists').exists(),
            body('email', 'Invalid email').exists().isEmail(),
            body('phone').optional().isInt()
          ]
        }
    }
  },
  register(req, res) {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      console.log(errors)
      return res.status(400).json({ errors: errors.array() });
    }

    return memberServices.create(req)
      .then(member => res.status(200).send("Register successfully"))
      .catch(error => res.status(400).send(error.errors));
  },

  async login(req, res) {
    return memberServices.login(req)
      .then(accessToken => res.status(200).send(accessToken))
      .catch(error => res.status(400).send(error.errors));
  },

  profile(req, res) {
    memberServices.getProfile(req)
      .then(member => res.status(200).send(member))
      .catch(error => res.status(400).send(error.errors));
  },

  async forgotPassword(req, res) {
    try {
      const email = req.body.email;
      const user = await member.findOne({
        where: { username: email }
      });
      if (user) {
        return res.status(200).send('Please check email');
      } else {
        res.send("Email doen't exist");
      }
    } catch (error) {
      console.log(error);
      res.status(500).send("Internal Server error Occured");
    }
  },

  async resetPassword(req, res) {
    const email = req.body.email;
    const user = await member.findOne({
      where: { username: email }
    });
    const salt = await bcrypt.genSaltSync(10);
    const password = bcrypt.hashSync(req.body.password, salt);
    user.password = password;
    user.save();
    res.status(200).send(user.email);
    return member
      .update({
        password: password
      }, { returning: true, where: { id: user.id } })
      .then(([rowsUpdate, [updatedRow]]) => res.status(200).send(updatedRow))
      .catch(error => res.status(400).send(error));
  },

  update(req, res) {
    return member
      .update({
        name: req.body.name,
        size: req.body.size,
        price: req.body.price,
        status: req.body.status
      }, { returning: true, where: { id: req.params.id } })
      .then(([rowsUpdate, [updatedRow]]) => res.status(200).send(updatedRow))
      .catch(error => res.status(400).send(error));
  },

  delete(req, res) {
    return member
      .destroy({
        where: {
          id: req.params.id
        }
      })
      .then(rowDeleted => {
        if (rowDeleted !== 1) {
          throw ({
            "name": "ValidationError",
            "errors": [{
              message: 'Item not found'
            }]
          });
        }
        return res.status(200).json({ message: "Deleted successfully" });
      })
      .catch(error => res.status(400).send(error));
  }

};