import models from "$models/index.js";
import { accessGrantHelpers, identityHelpers } from "$helpers/index.js";

const isOwner = (itemUser, requestUser) => {
  const itemUserId = itemUser?._id || itemUser;
  return itemUserId?.toString() === requestUser?._id?.toString();
};

export const ALL = async (req, res) => {
  try {
    const pageSize = req.query.pageSize ? parseInt(req.query.pageSize) : 20;
    const currentPage = req.query.page ? parseInt(req.query.page) : 1;
    const skip = pageSize * currentPage - pageSize;
    const query = {};
    const canAccessAllProfiles = accessGrantHelpers.hasAllResourceAccess(
      req.user,
      "profile",
    );

    if (!canAccessAllProfiles) {
      query.user = req.user._id;
    }

    const profile = await models.profile
      .find(query)
      .limit(pageSize)
      .skip(skip)
      .populate("user", identityHelpers.USER_IDENTITY_PROJECTION)
      .sort({ createdAt: -1 });

    const totalData = await models.profile.countDocuments(query);
    const totalPage = pageSize ? Math.ceil(totalData / pageSize) : 0;

    res.status(200).send({ profile, totalData, currentPage, totalPage });
  } catch (error) {
    const status = error.status || 500;
    const message = error.message || "خطا در دریافت profile";
    return res.status(status).send({ message });
  }
};

export const SINGLE = async (req, res) => {
  try {
    const { id } = req.params;
    const data = await models.profile
      .findById(id)
      .populate("user", identityHelpers.USER_IDENTITY_PROJECTION);

    if (!data) {
      return res.status(404).send({ message: "یافت نشد" });
    }

    if (
      !accessGrantHelpers.hasAllResourceAccess(req.user, "profile") &&
      !isOwner(data.user, req.user)
    ) {
      return res.status(403).send({ message: "دسترسی محدود" });
    }

    res.status(200).send(data);
  } catch (error) {
    const status = error.status || 500;
    const message = error.message || "خطا در دریافت profile";
    return res.status(status).send({ message });
  }
};

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

    const newItem = await models.profile.create(data);
    const populated = await models.profile
      .findById(newItem._id)
      .populate("user", identityHelpers.USER_IDENTITY_PROJECTION);

    res.status(201).send({
      message: "با موفقیت ایجاد شد",
      data: populated,
    });
  } catch (error) {
    const status = error.status || 500;
    const message = error.message || "خطا در ایجاد profile";
    return res.status(status).send({ message });
  }
};

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

    delete updateData.user;
    delete updateData._id;
    delete updateData.createdAt;
    delete updateData.updatedAt;

    const existingItem = await models.profile.findById(id);
    if (!existingItem) {
      return res.status(404).send({ message: "یافت نشد" });
    }

    if (
      !accessGrantHelpers.hasAllResourceAccess(req.user, "profile") &&
      !isOwner(existingItem.user, req.user)
    ) {
      return res.status(403).send({ message: "دسترسی محدود" });
    }

    const updated = await models.profile
      .findByIdAndUpdate(id, { $set: updateData }, { new: true })
      .populate("user", identityHelpers.USER_IDENTITY_PROJECTION);

    res.status(200).send({
      message: "با موفقیت ویرایش شد",
      data: updated,
    });
  } catch (error) {
    const status = error.status || 500;
    const message = error.message || "خطا در ویرایش profile";
    return res.status(status).send({ message });
  }
};

export const DELETE = async (req, res) => {
  try {
    const { id } = req.params;
    const existingItem = await models.profile.findById(id);

    if (!existingItem) {
      return res.status(404).send({ message: "یافت نشد" });
    }

    if (
      !accessGrantHelpers.hasAllResourceAccess(req.user, "profile") &&
      !isOwner(existingItem.user, req.user)
    ) {
      return res.status(403).send({ message: "دسترسی محدود" });
    }

    await models.profile.findByIdAndDelete(id);

    res.status(200).send({
      message: "با موفقیت حذف شد",
    });
  } catch (error) {
    const status = error.status || 500;
    const message = error.message || "خطا در حذف profile";
    return res.status(status).send({ message });
  }
};
