const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const Admin = require("../../models/Admin");

const jwtSecret = process.env.JWTSECRET;

// TODO: FORGOT PASSWORD

exports.authController = {
  signup: async (req, res) => {
    try {
      const { fullName, email, password } = req.body;

      const salt = bcrypt.genSaltSync(10);
      const hashedPassword = bcrypt.hashSync(password, salt);

      const admin = new Admin({
        fullName,
        email,
        password: hashedPassword,
      });

      await admin.save();

      const token = jwt.sign(
        {
          fullName,
          email,
          secret: "x8qMD@RQhK#t",
        },
        jwtSecret
      );

      return res.status(200).json({
        success: true,
        msg: "Account created successfully!",
        data: { token },
      });
    } catch (err) {
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
  login: async (req, res) => {
    try {
      const { email, password } = req.body;

      const admin = await Admin.findOne({ email });
      if (!admin) {
        return res
          .status(401)
          .json({ success: false, msg: "Invalid credetials" });
      }

      const isCorrect = bcrypt.compareSync(password, admin?.password);

      if (!isCorrect) {
        return res
          .status(401)
          .json({ success: false, msg: "Invalid credetials" });
      }

      const token = jwt.sign(
        {
          fullName: admin?.fullName,
          email,
          secret: "x8qMD@RQhK#t",
        },
        jwtSecret
      );
      return res.status(200).json({
        success: true,
        msg: "Logged in successfully",
        data: { token },
      });
    } catch (err) {
      console.log(err);
      return res
        .status(200)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
  forgotPassword: (req, res) => {
    return res.status(200).json({ success: true, msg: false });
  },
  resetPassword: async (req, res) => {
    try {
      const { token, newPassword } = req.body;

      const data = jwt.verify(token, jwtSecret);
      if (!data) {
        return res.status(403).json({ success: false, msg: "Forbidden" });
      }

      const admin = await Admin.findOne({ email: data.email });

      if (!admin) {
        return res.status(403).json({ success: false, msg: "Forbidden" });
      }
      const salt = bcrypt.genSaltSync(10);
      const hashedPassword = bcrypt.hashSync(newPassword, salt);

      admin.password = hashedPassword;
      await admin.save();

      return res
        .status(200)
        .json({ success: true, msg: "Password changed successfully!" });
    } catch (err) {
      console.log(err);
      return res
        .status(500)
        .json({ success: false, msg: "Something went wrong!" });
    }
  },
};
