require("dotenv").config();
const User = require("../../models").users;
const Department = require("../../models").departments;
const Activity = require("../helpers/activity.helper");
const jwt = require("jsonwebtoken");
const CryptoJS = require("crypto-js");
const secretKey = "4gt71TxD1e4P3433";
const Op = require("sequelize").Op;
var key = CryptoJS.enc.Base64.parse("4gt71TxD1e4P3433");
var iv = CryptoJS.enc.Base64.parse("4gt71TxD1e4P3433");
require("dotenv").config();
exports.Login = async (req, res) => {
  try {
    const { username, password, account_type } = req.body;

    if (!username) {
      return res.send({
        statusCode: "409",
        success: false,
        message: "Error",
        error: "Matric number is required",
      });
    }

    if (!password) {
      return res.send({
        statusCode: "409",
        success: false,
        message: "Error",
        error: "password is required",
      });
    }
    const user = await User.findOne({
      where: {
        username: username,
      },
      attributes: [
        "id",
        "password",
        "username",
        "first_login",
        "second_role",
        "role",
      ],
      raw: true,
    });
    if (!user) {
      return res.send({
        statusCode: "404",
        success: false,
        message: "Error",
        error: "An account doesn't exist with this username",
      });
    }
    // var encrypted = CryptoJS.AES.encrypt(password, key, {iv: iv});

    var decrypted = CryptoJS.AES.decrypt(user.password, key, {
      iv: iv,
    }).toString(CryptoJS.enc.Utf8);
    const match = decrypted === password;

    if (!match) {
      return res.send({
        statusCode: "409",
        success: false,
        message: "Error",
        error: "Invalid password",
      });
    }

    const token = jwt.sign(
      {
        username,
      },
      process.env.JWT_pa
    ); //will change it to .env variable for production

    const saveToken = await User.update(
      {
        remember_token: token,
      },
      {
        where: {
          username: username,
        },
      }
    );

    const saveActivity = await Activity("login", "User login", username);

    if (saveToken && saveActivity) {
      req.session.data = {
        token,
      };
      return res.status(200).send({
        statusCode: "200",
        success: true,
        message: "Success",
        token: token,
        user: user,
        error: undefined,
      });
    } else {
      return res.send({
        statusCode: "409",
        success: false,
        message: "Error",
        error: "An error ocurred, try again later",
      });
    }
  } catch (e) {
    console.log(e);
    res.status(500).send({
      statusCode: "500",
      success: false,
      message: "Error",
      error: e.message,
    });
  }
};

exports.Logout = async (req, res) => {
  try {
    const saveToken = await User.update(
      {
        remember_token: null,
      },
      {
        where: {
          username: req.user.username,
        },
      }
    );

    const saveActivity = await Activity(
      "logout",
      "User log out of the system",
      req.user.username
    );

    if (saveToken && saveActivity) {
      if (req.user.role == 7) {
        return res.redirect("/student-login");
      } else {
        return res.status(200).redirect("/staff-login");
      }
    }
  } catch (e) {
    if (req.user.role == 7 || req.user.role == "") {
      return res.render("login/student.ejs");
    } else {
      return res.render("login/staff.ejs");
    }
  }
};

exports.ForgetPassword = async (req, res) => {
  return res.render("login/fogot_password.ejs");
};

exports.firstLogin = async (req, res) => {
  const username = req.query?.id;
  let success = false;
  let error = false;
  if (!username) res.redirect("/student-dashboard");

  const departments = await Department.findAll({});
  return res.render("login/first-time.ejs", {
    success,
    error,
    username,
    departments,
  });
};
