const AdminConversations = require("../../models/ConversationsAdmin");
const AdminChatConversations = require("../../models/ChatConversationsAdmin");
const Customers = require("../../models/Customers");
const SystemUser = require("../../models/SystemUser");

const {
  agentCustomerDetailsExcludes,
} = require("../../helpers/model-excludes-attributes/excludes");

exports.getConversation = (req, res, next) => {
  const { customerId: buyer_id } = req;

  const { adminId: admin_id } = req.params;
  AdminConversations.findOne({
    where: {
      buyer_id,
      admin_id,
    },
  })
    .then((adminConversations) => {
      if (!adminConversations) {
        return AdminConversations.create({
          buyer_id,
          admin_id,
          last_updated: new Date(),
        }).then((newAdminConversation) => {
          res.status(201).json({
            success: true,
            conversation_id: newAdminConversation.id,
          });
        });
      }

      res
        .status(200)
        .json({ success: true, conversation_id: adminConversations.id });
    })
    .catch((err) => {
      next(err);
    });
};

exports.getChatsCustomerAndAdmin = (req, res, next) => {
  const { conversationId } = req.params;
  const { customerId: buyer_id } = req;
  const page = req.query.page ? parseInt(req.query.page) : 1;
  const pageSize = req.query.pageSize ? parseInt(req.query.pageSize) : 10;

  const offset = (page - 1) * pageSize;

  AdminConversations.findOne({
    where: {
      buyer_id,
      id: conversationId,
    },
  })
    .then((adminConversationId) => {
      if (!adminConversationId) {
        return res.status(200).json({
          success: false,
          msg: "Invalid conversation Id.",
        });
      }
      return AdminChatConversations.findAndCountAll({
        where: {
          conversation_id: adminConversationId.id,
        },
        include: [
          {
            model: Customers,
            as: "buyer",
            attributes: {
              exclude: agentCustomerDetailsExcludes(),
            },
          },
          {
            model: SystemUser,
            as: "admin",
          },
        ],
        order: [["created_on", "DESC"]],
        limit: pageSize,
        offset: offset,
      });
    })
    .then((result) => {
      const { count, rows } = result;
      const totalPages = Math.ceil(count / pageSize);

      res.status(200).json({
        success: true,
        conversationId,
        chats: rows,
        totalChats: count,
        totalPages: totalPages,
        currentPage: page,
      });
    })
    .catch((err) => next(err));
};

exports.sendMessageToAdmin = (req, res, next) => {
  const { customerId: buyer_id } = req;
  const { conversation_id: conversation_id, message } = req.body;

  AdminConversations.findOne({
    where: {
      id: conversation_id,
      buyer_id,
    },
  })
    .then((conversation) => {
      if (!conversation)
        return res
          .status(200)
          .json({ success: false, msg: "Conversation does not exists!" });

      const admin_id = conversation.admin_id;

      return new AdminChatConversations({
        buyer_id,
        admin_id,
        message,
        created_on: new Date(),
        isSeen_Buyer: 1,
        isSeen_Admin: 0,
        conversation_id,
      }).save();
    })
    .then((newRecord) => {
      res.status(200).json({ success: true, chats: newRecord });
    })
    .catch((err) => {
      next(err);
    });
};
