var bcrypt = require("bcryptjs");
var User = require("../models/User");

function createUser(req, res) {
  var username = req.body.username ? req.body.username.trim() : "";
  var password = req.body.password;

  if (!username || !password) {
    return res.status(400).json({ message: "Username and password are required" });
  }

  if (password.length < 6) {
    return res.status(400).json({ message: "Password must have at least 6 characters" });
  }

  User.findOne({ username: username })
    .then(function (userExists) {
      if (userExists) {
        return res.status(409).json({ message: "Username already exists" });
      }

      return bcrypt.hash(password, 10);
    })
    .then(function (encryptedPassword) {
      if (!encryptedPassword) {
        return null;
      }

      return User.create({ username: username, password: encryptedPassword });
    })
    .then(function (user) {
      if (!user) {
        return;
      }

      req.session.user = { id: user._id, username: user.username };

      req.session.save(function (error) {
        if (error) {
          return res.status(500).json({ message: "Failed to save user session" });
        }

        res.status(201).json({
          message: "User created successfully",
          user: req.session.user,
        });
      });
    })
    .catch(function (error) {
      res.status(500).json({ message: "Failed to create user", error: error.message });
    });
}

function loginUser(req, res) {
  var username = req.body.username ? req.body.username.trim() : "";
  var password = req.body.password;
  var savedUser = null;

  if (!username || !password) {
    return res.status(400).json({ message: "Username and password are required" });
  }

  User.findOne({ username: username })
    .then(function (user) {
      if (!user) {
        return null;
      }

      savedUser = user;
      return bcrypt.compare(password, user.password);
    })
    .then(function (passwordIsCorrect) {
      if (!savedUser || !passwordIsCorrect) {
        return res.status(401).json({ message: "Invalid username or password" });
      }

      req.session.user = { id: savedUser._id, username: savedUser.username };

      req.session.save(function (error) {
        if (error) {
          return res.status(500).json({ message: "Failed to save login session" });
        }

        res.status(200).json({
          message: "Login successful",
          user: req.session.user,
        });
      });
    })
    .catch(function (error) {
      res.status(500).json({ message: "Login failed", error: error.message });
    });
}

function recoverPassword(req, res) {
  var username = req.body.username ? req.body.username.trim() : "";
  var newPassword = req.body.newPassword;
  var savedUser = null;

  if (!username || !newPassword) {
    return res.status(400).json({ message: "Username and new password are required" });
  }

  if (newPassword.length < 6) {
    return res.status(400).json({ message: "New password must have at least 6 characters" });
  }

  User.findOne({ username: username })
    .then(function (user) {
      if (!user) {
        return null;
      }

      savedUser = user;
      return bcrypt.hash(newPassword, 10);
    })
    .then(function (encryptedPassword) {
      if (!savedUser) {
        return res.status(404).json({ message: "User not found" });
      }

      savedUser.password = encryptedPassword;
      return savedUser.save();
    })
    .then(function (user) {
      if (!user) {
        return;
      }

      res.status(200).json({ message: "Password recovered successfully" });
    })
    .catch(function (error) {
      res.status(500).json({ message: "Password recovery failed", error: error.message });
    });
}

function logoutUser(req, res) {
  req.session.destroy(function (error) {
    if (error) {
      return res.status(500).json({ message: "Logout failed" });
    }

    res.clearCookie("connect.sid");
    res.status(200).json({ message: "Logout successful" });
  });
}

function getSessionUser(req, res) {
  res.status(200).json({ user: req.session.user || null });
}

module.exports = {
  createUser: createUser,
  loginUser: loginUser,
  recoverPassword: recoverPassword,
  logoutUser: logoutUser,
  getSessionUser: getSessionUser,
};
