import models from "$models/index.js";

export const ALL = async (req, res) => {
  try {
    const pageSize = req.query.pageSize ? parseInt(req.query.pageSize) : 0;
    const currentPage = req.query.page ? parseInt(req.query.page) : 0;

    const skip = pageSize * currentPage - pageSize;

    const roles = await models.role.find().limit(pageSize).skip(skip);
    const totalData = await models.role.countDocuments({});
    const totalPage = pageSize ? Math.ceil(totalData / pageSize) : 0;

    res.status(200).send({ roles, totalData, currentPage, totalPage });
  } catch (error) {
    res.status(500).send({ message: error.message });
  }
};

export const SINGLE = async (req, res) => {
  try {
    const { id } = req.params;

    const role = await models.role.findById(id);

    if (role) {
      res.status(200).send({ role });
    } else {
      res.status(404).send({ message: "role did not found" });
    }
  } catch (error) {
    res.status(500).send({ message: error.message });
  }
};

export const CREATE = async (req, res) => {
  try {
    let data = req.body;

    // Prevent creating superAdmin roles via API
    if (data.isSuperAdmin === true) {
      return res.status(403).send({
        message:
          "SuperAdmin roles can only be created via init-database script",
      });
    }

    const newRole = new models.role(data);
    const role = await newRole.save();

    res.status(200).send({ message: "role created", role });
  } catch (error) {
    res.status(500).send({ message: error.message });
  }
};

export const UPDATE = async (req, res) => {
  try {
    const { id } = req.params;
    let data = req.body;

    // Check if role exists first
    const existingRole = await models.role.findById(id);
    if (!existingRole) {
      return res.status(404).send({ message: "role did not found" });
    }

    // Prevent modifying superAdmin status
    if (existingRole.isSuperAdmin === true) {
      return res.status(403).send({
        message: "SuperAdmin role cannot be modified",
      });
    }

    // Prevent setting isSuperAdmin to true via API
    if (data.isSuperAdmin === true) {
      return res.status(403).send({
        message: "Cannot set isSuperAdmin via API",
      });
    }

    const role = await models.role.findByIdAndUpdate(id, data);

    if (role) {
      res.status(200).send({ message: "role updated" });
    } else {
      res.status(404).send({ message: "role did not found" });
    }
  } catch (error) {
    res.status(500).send({ message: error.message });
  }
};

export const DELETE = async (req, res) => {
  try {
    const { id } = req.params;

    // Check if role exists first
    const role = await models.role.findById(id);
    if (!role) {
      return res.status(404).send({ message: "role did not found" });
    }

    // Prevent deleting superAdmin role
    if (role.isSuperAdmin === true) {
      return res.status(403).send({
        message: "SuperAdmin role cannot be deleted",
      });
    }

    await models.role.findByIdAndDelete(id);
    res.status(200).send({ message: "role deleted" });
  } catch (error) {
    res.status(500).send({ message: error.message });
  }
};

export const UPDATE_PRIORITY = async (req, res) => {
  const { orderedData } = req.body;

  const updatedPriority = [];
  let status = 200;

  await Promise.all(
    orderedData.map(async ({ _id, priority }) => {
      try {
        await models.role.findOneAndUpdate({ _id }, { $set: { priority } });
        updatedPriority.push({
          _id,
          priority,
        });
      } catch (error) {
        updatedPriority.push({ _id, priority, error });
        status = 500;
      }
    }),
  );

  res.status(status).send({ updatedPriority });
};
