import models from "$models/index.js";
import { identityHelpers } from "$helpers/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 userInfos = await models.userInfo
      .find()
      .limit(pageSize)
      .skip(skip)
      .populate("user", identityHelpers.USER_IDENTITY_PROJECTION);
    const totalData = await models.userInfo.countDocuments({});
    const totalPage = pageSize ? Math.ceil(totalData / pageSize) : 0;

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

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

    const userInfo = await models.userInfo
      .findById(id)
      .populate("user", identityHelpers.USER_IDENTITY_PROJECTION);

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

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

    const newUserInfo = new models.userInfo(data);
    const userInfo = await newUserInfo.save();

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

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

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

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

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

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

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