const jwt = require("jsonwebtoken");
const User = require("../models/userModel");
const moment = require("moment/moment");
const generator = require("generate-password");

const sgMail = require("@sendgrid/mail");
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const signToken = (id) => {
  return jwt.sign({ id }, process.env.JWT_SECRET, {
    expiresIn: 7200000,
  });
};

const verification = (token) => {
  return jwt.verify(token, process.env.JWT_SECRET);
};

const sendEmail = async ({ recipients, subject, body }) => {
  const msg = {
    to: recipients,
    from: "winzco@outlook.com",
    subject: subject,
    html: body,
  };
  sgMail
    .send(msg)
    .then(() => {
      return "Email sent";
    })
    .catch((error) => {
      return error;
    });
};

// exports.Adminlogin = async (req, res, next) => {
//   const { email, password } = req.body;
//   // check if email password exist
//   if (!email || !password) {
//     res.json({
//       token: [],
//       message: "Please provide email and password!",
//       IsSuccess: false,
//     });
//     // return next(new AppError("Please provide email and password!", 400));
//     return next();
//   }

//   //check if user exist and password is correct
//   const user = await User.findOne({ emailAddress: email }).select("+password");
//   console.log(user);
//   if (!user || !(await user.correctPassword(password, user.password))) {
//     res.json({
//       token: [],
//       message: "Incorrect Email or  Password.",
//       IsSuccess: false,
//     });
//     // return next(new AppError("Incorrect Email or  Password.", 401));
//     return next();
//   }
//   //check if everything ok, send token to client
//   const Token = signToken(user._id);
//   res.json({
//     message: "User logged in successfully",
//     IsSuccess: true,
//     Status_Code: 200,
//     Data: {
//       Token,
//       User: { id: user._id, User_Photo_Path: null, Role_Id: 2 },
//     },
//   });
// };
exports.signin = async (req, res, next) => {
  const { email, password } = req.body;
  // check if email password exist
  if (!email || !password) {
    res.json({
      token: [],
      message: "Please provide email and password!",
      IsSuccess: false,
    });
    // return next(new AppError("Please provide email and password!", 400));
    return next();
  }

  //check if user exist and password is correct
  const user = await User.findOne({ emailAddress: email }).select("+password");
  // console.log(user);
  if (!user || !(await user.correctPassword(password, user.password))) {
    res.json({
      token: [],
      message: "Incorrect Email or  Password.",
      IsSuccess: false,
    });
    // return next(new AppError("Incorrect Email or  Password.", 401));
    return next();
  }

  if (user.userGroup == "mobileApp") {
    res.json({
      token: [],
      message: "Incorrect Email or  Password.",
      IsSuccess: false,
    });
    // return next(new AppError("Incorrect Email or  Password.", 401));
    return next();
  }
  //check if everything ok, send token to client
  const Token = signToken(user._id);
  res.json({
    message: "User logged in successfully",
    IsSuccess: true,
    Status_Code: 200,
    Data: {
      Token,
      User: {
        id: user._id,
        firstName: user.firstName,
        lastName: user.lastName,
        emailAddress: user.emailAddress,
        currency: user.currency,
        User_Photo_Path: null,
        Role_Id: 2,
      },
    },
  });
};

exports.appSignin = async (req, res, next) => {
  const { email, password } = req.body;
  // check if email password exist
  if (!email || !password) {
    res.json({
      token: [],
      message: "Please provide email and password!",
      IsSuccess: false,
    });
    // return next(new AppError("Please provide email and password!", 400));
    return next();
  }

  //check if user exist and password is correct
  const user = await User.findOne({ emailAddress: email }).select("+password");
  // console.log(user);
  if (!user || !(await user.correctPassword(password, user.password))) {
    res.json({
      token: [],
      message: "Incorrect Email or  Password.",
      IsSuccess: false,
    });
    // return next(new AppError("Incorrect Email or  Password.", 401));
    return next();
  }

  if (user.userGroup !== "mobileApp") {
    res.json({
      token: [],
      message: "Incorrect Email or  Password.",
      IsSuccess: false,
    });
    // return next(new AppError("Incorrect Email or  Password.", 401));
    return next();
  }
  //check if everything ok, send token to client
  const Token = signToken(user._id);
  res.json({
    message: "User logged in successfully",
    IsSuccess: true,
    Status_Code: 200,
    Data: {
      Token,
      User: {
        id: user._id,
        firstName: user.firstName,
        lastName: user.lastName,
        emailAddress: user.emailAddress,
        currency: user.currency,
        exchangeRate: user.exchangeRate,
        User_Photo_Path: null,
        Role_Id: 2,
      },
    },
  });
};

exports.signUp = async (req, res, next) => {
  const data = req.body;
  const body = {
    emailAddress: data.emailAddress,
    firstName: data.firstName,
    lastName: data.lastName,
    password: data.password,
    passwordConfirm: data.passwordConfirm,
    country: data.country,
    contact: data.contact,
    userGroup: "mobileApp",
    currency: "AED",
    exchangeRate: 1,
    IsActive: true,
    IsDelete: false,
    CreatedBy: data.User ? data.User : "MobileApp",
    CreatedOn: moment().format("YYYY-MM-DDTHH:mm:ss"),
  };

  const newUser = await User.create(body);

  res.json({
    message: "Signed Up Successfully.",
    IsSuccess: true,
    Status_Code: 200,
    Data: newUser,
  });
};

exports.forgetPassword = async (req, res, next) => {
  const data = req.body;

  const foundUser = await User.find({ emailAddress: data.emailAddress });
  if (foundUser.length > 0) {
    const passcode = generator.generate({
      length: 8,
      numbers: true,
      uppercase: false,
    });

    sendEmail({
      recipients: data.emailAddress,
      subject: "Reset Password Email",
      body:
        "Dear User,<br><br>Your password has been reset to following:<br>" +
        passcode +
        "<br><br>It is recommended to change your password after your successfully sign into your account.<br><br>This is system generated email do not reply.</b> <br> Regards,<br> Team Winzco.",
    });

    const updateUser = await User.updateOne(
      { _id: foundUser[0]._id },
      {
        $set: {
          password: passcode,
          ModifiedBy: "Password Reset",
          ModifiedOn: moment().format("YYYY-MM-DD"),
        },
      }
    );

    res.json({
      message: "Password reset email sent Successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: null,
    });
  } else {
    res.json({
      message: "You have not registered yet.",
      IsSuccess: true,
      Status_Code: 204,
      Data: null,
    });
  }
};

exports.changePassword = async (req, res, next) => {
  const data = req.body;

  const foundUser = await User.find({ _id: data.userID });
  if (foundUser.length > 0) {
    const updateUser = await User.updateOne(
      { _id: foundUser[0]._id },
      {
        $set: {
          password: data.password,
          ModifiedBy: "Password Changed by Users",
          ModifiedOn: moment().format("YYYY-MM-DD"),
        },
      }
    );

    res.json({
      message: "Password updated Successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: null,
    });
  } else {
    res.json({
      message: "User not found.",
      IsSuccess: false,
      Status_Code: 204,
      Data: null,
    });
  }
};
