const jwt = require("jsonwebtoken");
const User = require("../models/userModel");
const moment = require("moment/moment");

const verification = async (token) => {
  try {
    if (token.startsWith("Bearer ")) {
      TokenArray = token.split(" ");
      const decoded = jwt.verify(TokenArray[1], process.env.JWT_SECRET);
      const user = await User.findOne({ _id: decoded.id });
      if (user !== null && decoded.exp > Date.now() / 1000) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  } catch (error) {
    return false;
  }
};

exports.getUsers = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const Users = await User.find({ IsDelete: false });
    res.setHeader("Content-Type", "application/javascript");
    res.status(200).send({
      message: "",
      IsSuccess: true,
      Status_Code: 200,
      Data: Users,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.getUsersDropdown = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const Users = await User.find(
      { IsDelete: false }, // Query criteria
      { firstName: 1, lastName: 1, _id: 1 } // Projection to include only name and _id fields
    );
    res.setHeader("Content-Type", "application/javascript");
    res.status(200).send({
      message: "",
      IsSuccess: true,
      Status_Code: 200,
      Data: Users,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.saveUser = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const body = req.body;
    const Users = await User.find();
    const data = {
      emailAddress: body.emailAddress,
      firstName: body.firstName,
      lastName: body.lastName,
      password: body.password,
      country: body.country,
      contact: body.contact,
      currency: body.currency,
      userGroup: body.userGroup,
      exchangeRate: 1,
      IsActive: body.IsActive,
      IsDelete: false,
      CreatedBy: body.User ? body.User : "MobileApp",
      CreatedOn: moment().format("YYYY-MM-DD"),
    };
    const newUser = await User.create(data);
    res.json({
      message: "New User created successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: newUser,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.editUser = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const body = req.body;
    const updateUser = await User.updateOne(
      { _id: body._id },
      {
        $set: {
          emailAddress: body.emailAddress,
          firstName: body.firstName,
          lastName: body.lastName,
          country: body.country,
          contact: body.contact,
          currency: body.currency,
          userGroup: body.userGroup,
          IsActive: body.IsActive,
          ModifiedBy: body.User,
          ModifiedOn: moment().format("YYYY-MM-DD"),
        },
      }
    );
    const updatedUser = await User.findOne({ _id: body._id });
    res.json({
      message: "User updated successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: updatedUser,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.updateUser = async (req, res, next) => {
  const body = req.body;
  const updateUser = await User.updateOne(
    { _id: body._id },
    {
      $set: {
        emailAddress: body.emailAddress,
        firstName: body.firstName,
        lastName: body.lastName,
        // country: body.country,
        // contact: body.contact,
        currency: body.currency,
        exchangeRate: body.exchangeRate,
        ModifiedBy: body.User,
        ModifiedOn: moment().format("YYYY-MM-DD"),
      },
    }
  );
  const updatedUser = await User.findOne({ _id: body._id });
  res.json({
    message: "User updated successfully.",
    IsSuccess: true,
    Status_Code: 200,
    Data: updatedUser,
  });
};

exports.deleteUser = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const body = req.body;
    const updateUser = await User.updateOne(
      { User_Id: body.User_Id },
      {
        $set: {
          IsActive: body.IsActive,
          IsDelete: body.IsDelete,
          ModifiedBy: body.User,
          ModifiedOn: moment().format("YYYY-MM-DD"),
        },
      }
    );
    const updatedUser = await User.findOne({ User_Id: body.User_Id });
    res.json({
      message: "User deleted successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: updatedUser,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.changeUserStatus = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const body = req.body;
    const updateUser = await User.updateOne(
      { User_Id: body.User_Id },
      {
        $set: {
          IsActive: body.IsActive,
          ModifiedBy: body.User,
          ModifiedOn: moment().format("YYYY-MM-DD"),
        },
      }
    );
    const updatedUser = await User.findOne({ User_Id: body.User_Id });
    res.json({
      message: "User status changed successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: updatedUser,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};
