const { createAuditTrail } = require("../../helpers/sellerAuditTrail.service");
const Chats = require("../../models/Chats");
const Conversations = require("../../models/Conversations");
const Customers = require("../../models/Customers");
const SellersCompany = require("../../models/SellersCompany");

exports.getConversations = async (req, res, next) => {
  const { seller_id } = req;

  try {
    const conversations = await Conversations.findAll({
      where: {
        seller_id,
      },
      include: [
        {
          model: Customers,
          as: "customer_detail",
          attributes: ["id", "first_name", "last_name", "hardware_name"],
        },
        {
          model: SellersCompany,
          as: "seller_company",
          attributes: ["id", "company_name", "shop_name"],
        },
        {
          model: Chats,
          as: "chats_detail",
          attributes: [
            "id",
            "created_on",
            "message",
            "buyer_id",
            "seller_id",
            "isSeen_seller",
          ],
          include: [
            {
              model: Customers,
              as: "buyer",
              attributes: ["id", "first_name", "last_name", "hardware_name"],
            },
            {
              model: SellersCompany,
              as: "seller",
              attributes: ["id", "company_name", "shop_name"],
            },
          ],
          limit: 1,
          order: [["created_on", "DESC"]],
        },
      ],
      attributes: ["id", "last_updated"],
      order: [["last_updated", "DESC"]],
    });

    res.status(200).json({ success: true, conversations });
  } catch (err) {
    next(err);
  }
};

exports.getChatsByConversationId = async (req, res, next) => {
  const { seller_id } = req;
  const { conversation_id } = req.query;

  try {
    const conversation = await Conversations.findOne({
      where: {
        seller_id,
        id: conversation_id,
      },
    });

    if (!conversation)
      return res
        .status(401)
        .json({ success: false, message: "Conversation not found." });

    const chats = await Chats.findAll({
      where: {
        conversation_id,
      },
      attributes: [
        "id",
        "created_on",
        "message",
        "buyer_id",
        "seller_id",
        "isSeen_seller",
      ],
      include: [
        {
          model: Customers,
          as: "buyer",
          attributes: ["id", "first_name", "last_name", "hardware_name"],
        },
        {
          model: SellersCompany,
          as: "seller",
          attributes: ["id", "company_name", "shop_name"],
        },
      ],
      order: [["created_on", "DESC"]],
    });
    res.status(200).json({ success: true, chats });
  } catch (err) {
    next(err);
  }
};

exports.sendMessageByConversationId = async (req, res, next) => {
  const { seller_id, seller_account_id } = req;
  const { conversation_id } = req.query;

  const { message } = req.body;
  try {
    const conversation = await Conversations.findOne({
      where: {
        seller_id,
        id: conversation_id,
      },
    });

    if (!conversation)
      return res
        .status(401)
        .json({ success: false, message: "Conversation not found." });

    const messageResponse = await Chats.create({
      conversation_id,
      seller_id,
      message,
      created_on: new Date(),
      isSeen_seller: 1,
      isSeen_buyer: 0,
    });

    const trail = await createAuditTrail({
      seller_id: seller_account_id,
      seller_company_id: seller_id,
      module: "Chat",
      action: "create - Send Message",
      action_description: `ID: ${messageResponse.id}, Conversation ID: ${conversation_id}`,
    });

    res.status(200).json({ success: true, message: messageResponse });
  } catch (err) {
    next(err);
  }
};
