const router = require("express").Router();
const cookie_parser = require("cookie-parser");
const CryptoJS = require("crypto-js");
const jwt = require("jsonwebtoken");
const {
  verify_token,
  verify_token_and_authorization,
  verify_token_and_admin,
} = require("./verify_token");
router.use(cookie_parser());

router.post("/register", async (req, res) => {
  try {
    const new_user = await User.create({
      username: req.body.username,
      email: req.body.email,
      password: CryptoJS.AES.encrypt(
        req.body.password,
        "hgiufhrwoijcjvj"
      ).toString(),
    });

    res.status(200).json(new_user);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

router.post("/login", async (req, res) => {
  try {
    const user = await User.findOne({ username: req.body.username });
    !user && res.status(401).json("Wrong credentials");

    const password1 = req.body.password;

    const original_password = CryptoJS.AES.decrypt(
      user.password,
      "hgiufhrwoijcjvj"
    ).toString(CryptoJS.enc.Utf8);


    if (password1 !== original_password) {
      res.status(401).json("Wrong credentials");
    }

    const access_token = jwt.sign(
      {
        id: user._id, //payloads
        is_admin: user.is_admin, //payload
      },
      "uygferuiheio",
      { expiresIn: "3d" }
    );

    res.cookie("login", access_token, {
      expires: new Date(Date.now() + 50000),
      httpOnly: true,
    });

    res.status(200).json({ user, access_token });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

router.get("/logout", verify_token_and_authorization, async (req, res) => {
  res.cookie("login", "", { maxAge: 1 });
  const access_token = { expiresIn: "1s" };

  res.json({ message: "User logged out" });
});

module.exports = router;
