const formidable = require("formidable");
const validator = require("validator");
const User = require("../models/authModel");
const fs = require("fs");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const crypto = require("crypto")


class authController {
  registerPage = (req, res) => {
    const { curdToken } = req.cookies;
    if (curdToken) {
      return res.redirect("/dashboard");
    } else {
      return res.render("dashboard/register", { error: "" });
    }
  };
  loginPage = (req, res) => {
    const { curdToken } = req.cookies;
    if (curdToken) {
      return res.redirect("/dashboard");
    } else {
      return res.render("dashboard/login", { error: "" });
    }
  };

  userRegister = async (req, res) => {
    const form = formidable({ multiples: true });
    form.parse(req, async (err, fields, files) => {
      const {
        nomor_induk,
        nama,
        jenis_kelamin,
        semester,
        program_studi,
        fakultas,
        alamat,
        email,
        no_telpon,
        password,
      } = fields;
      const code = [`${crypto.randomBytes(3).toString("hex")}`]

      const error = {};

      if (validator.isEmpty(nomor_induk) || isNaN(nomor_induk)) {
        error.nomor_induk = "Please provide your NIM";
      }
      if (!nomor_induk.startsWith("22") && !nomor_induk.startsWith("23") && !nomor_induk.startsWith("24")) {
        error.nomor_induk = "Nomor induk must start with 22, 23, or 24";
      }
      if (validator.isEmpty(nama)) {
        error.nama = "Please provide your name";
      }
      if (validator.isEmpty(jenis_kelamin)) {
        error.jenis_kelamin = "Please provide your gender";
      }
      if (validator.isEmpty(semester) || isNaN(semester)) {
        error.semester = "Please provide your semester";
      }
      if (validator.isEmpty(program_studi)) {
        error.program_studi = "Please provide your study program";
      }
      if (validator.isEmpty(fakultas)) {
        error.fakultas = "Please provide your faculty";
      }
      if (validator.isEmpty(alamat)) {
        error.alamat = "Please provide your address";
      }
      if (validator.isEmpty(email)) {
        error.email = "Please provide your email";
      }
      if (!validator.isEmpty(email) && !validator.isEmail(email)) {
        error.email = "Please provide valid email";
      }
      if (validator.isEmpty(no_telpon)) {
        error.no_telpon = "Please provide your telephone";
      }
      if (validator.isEmpty(password)) {
        error.password = "Please provide your password";
      }
      if (password.length < 6 || password.length > 9) {
        error.password = "Password must be between 6 and 9 characters";
      }
      if (Object.keys(error).length > 0) {
        return res.render("dashboard/register", { error });
      } else {
        try {
          const user = await User.findById(nomor_induk);
          if (user) {
            return res.render("sweet-alert", {
              icon: "error",
              message: "NIM already exist",
              redirectUrl: "/register",
            });
          } else {
            const createUser = new User(
              nomor_induk,
              nama,
              jenis_kelamin,
              semester,
              program_studi,
              fakultas,
              alamat,
              email,
              no_telpon,
              await bcrypt.hash(password, 9),
              jenis_kelamin == "Perempuan" ? "mahasiswi.png" : "mahasiswa.png",
              "1",
              code,
              "",
            );
            await createUser.save();

            const token = jwt.sign(
              {
                id: nomor_induk,
              },
              "affidev",
              {
                expiresIn: "3d",
              }
            );

            res.cookie("curdToken", token, {
              expires: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000),
            });

            return res.render("sweet-alert", {
              icon: "success",
              message: "Your register successfull",
              redirectUrl: "/dashboard",
            });
          }
        } catch (error) {}
      }
    });
  };
  userLogin = async (req, res) => {
    const { nomor_induk, password } = req.body;
    const error = {};
    if (validator.isEmpty(nomor_induk) || isNaN(nomor_induk)) {
      error.nomor_induk = "Please provide your NIM/NIDN";
    }
    if (validator.isEmpty(password)) {
      error.password = "Please provide your password";
    }
    if (Object.keys(error).length > 0) {
      return res.render("dashboard/login", { error });
    } else {
      try {
        const user = await User.findById(nomor_induk);
        if (user) {
          const matchPassword = await bcrypt.compare(password, user.password);
          if (matchPassword) {
            const token = jwt.sign(
              {
                id: user.nomor_induk,
              },
              "affidev",
              {
                expiresIn: "3d",
              }
            );

            res.cookie("curdToken", token, {
              expires: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000),
            });

            return res.render("sweet-alert", {
              icon: "success",
              message: "Your login successful",
              redirectUrl: "/dashboard",
            });
          } else {
            return res.render("sweet-alert", {
              icon: "error",
              message: "Your password invalid",
              redirectUrl: "/login",
            });
          }
        } else {
          return res.render("sweet-alert", {
            icon: "error",
            message: "Nomor Induk does not exist",
            redirectUrl: "/login",
          });
        }
      } catch (error) {}
    }
  };
}
module.exports = new authController();
