const whispir = require("../../helpers/whispir");
const smsTemplates = require("../../helpers/sms-no-templates/sms-no-templates");
const OrderForm = require("../../models/OrderForm");
const Customers = require("../../models/Customers");
const SellersCompany = require("../../models/SellersCompany");
const {
  filterAndFormatPhones,
  formatDate12Hour,
  SELLER_EXPEDITE_ORDERS,
} = require("../../helpers/common");
const SellerFeatureFlags = require("../../models/SellerFeatureFlags");
const SellerControlFeatureFlags = require("../../models/SellerControlFeatureFlags");
const OrderFormDetails = require("../../models/OrderFormDetails");
const Products = require("../../models/Products");
exports.customMessage = async (req, res, next) => {
  const { custom, recipientNumber } = req.body;

  const whispirReqBody = {
    customTemplate: custom,
    recipientNumber,
  };
  try {
    const whispirResponse = await whispir.messaging.singleMessage(
      whispirReqBody,
      "custom",
    );
    res.status(200).json({ success: true, msg: "SMS sent successfully" });
  } catch (err) {
    next(err);
  }
};

exports.orderVerified = async (req, res, next) => {
  const { reference_no } = req.body;

  if (!reference_no)
    res.status(401).json({ success: false, message: "Missing reference no!" });

  try {
    const orderForm = await OrderForm.findOne({
      where: {
        reference_no,
      },
      attributes: ["id", "reference_no", "customer_id", "shipping_type"],
      include: [
        {
          model: Customers,
          as: "customer_detail",
          attributes: [
            "first_name",
            "last_name",
            "hardware_name",
            "phone",
            "phone_2",
            "phone_3",
          ],
        },
        {
          model: SellersCompany,
          as: "sellers_company_details",
          attributes: [
            "id",
            "phone_number_primary",
            "phone_number_optional",
            "phone_number_optional_2",
          ],
        },
        {
          model: OrderFormDetails,
          as: "order_form_details",
          attributes: ["id", "product_id", "quantity"],
          include: [
            {
              model: Products,
              as: "product",
              attributes: ["id", "menu"],
            },
          ],
        },
      ],
    });

    const orderProductDetails = [];
    orderForm?.order_form_details?.forEach((detail) => {
      orderProductDetails.push({
        product_id: detail.product_id,
        quantity: detail.quantity,
        menu: detail?.product?.menu,
      });
    });

    const customerPhones = filterAndFormatPhones([
      orderForm?.customer_detail?.phone,
      orderForm?.customer_detail?.phone_2,
      orderForm?.customer_detail?.phone_3,
    ]);

    const sellerPhones = filterAndFormatPhones([
      orderForm?.sellers_company_details?.phone_number_primary,
      orderForm?.sellers_company_details?.phone_number_optional,
      orderForm?.sellers_company_details?.phone_number_optional_2,
      "09178341220", // Michael
      "09178255105", // NSM Edmar
      "09178000347", // Boss RLJ
      "09171804591", // Jiggs
    ]);

    const customerSmsTemplate = smsTemplates.orderVerified(
      `${orderForm?.customer_detail?.first_name} ${orderForm?.customer_detail?.last_name}`,
      reference_no,
      orderProductDetails,
    );

    const sellersSmsTemplate =
      smsTemplates.sellerWarehouseMenSmsTemplateOrderPlaced(
        `${orderForm?.customer_detail?.first_name} ${orderForm?.customer_detail?.last_name}`,
        orderForm?.customer_detail?.hardware_name,
        reference_no,
        formatDate12Hour(new Date()),
        orderForm?.shipping_type === "Standard Shipping" ||
          orderForm?.shipping_type === "Hardware Shipping",
        orderProductDetails,
      );
    // SELLER_EXPEDITE_ORDERS
    const sellerFeaturesFlagPromise = SellerFeatureFlags.findOne({
      where: {
        name: SELLER_EXPEDITE_ORDERS,
        status: true,
      },
    });
    // SELLER_EXPEDITE_ORDERS
    const [sellerFeaturesFlag] = await Promise.all([sellerFeaturesFlagPromise]);

    // SELLER_EXPEDITE_ORDERS
    if (sellerFeaturesFlag) {
      const sellerControlFlag = await SellerControlFeatureFlags.findOne({
        where: {
          feature_flag_id: sellerFeaturesFlag.id,
          seller_company_id: orderForm?.sellers_company_details?.id,
          enabled: true,
          status: true,
        },
      });

      let orderStatus = "Verified";
      if (sellerControlFlag) {
        if (orderForm?.shipping_type === "Pick-up") {
          // Pickup Orders
          orderStatus = "Release Order - Customer Pickup";
        } else {
          // For Delivery Orders
          orderStatus = "Release Order - Delivery";
        }

        orderForm.status = orderStatus;
        await orderForm.save();
      }
    }
    // SELLER_EXPEDITE_ORDERS

    if (customerPhones.length > 0) {
      const whispirText = await whispir.messaging.singleMessage(
        {
          recipientNumber: customerPhones.join(","),
          customTemplate: customerSmsTemplate,
        },
        "custom"
      );
    }

    if (sellerPhones.length > 0) {
      const whispirText = await whispir.messaging.singleMessage(
        {
          recipientNumber: sellerPhones.join(","),
          customTemplate: sellersSmsTemplate,
        },
        "custom"
      );
    }

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