const SellerCompany = require("../../models/SellersCompany");
const OrderForm = require("../../models/OrderForm");
const OrderFormDetails = require("../../models/OrderFormDetails");
const { Op } = require("sequelize");
const Products = require("../../models/Products");
const ProductVariation = require("../../models/ProductVariation");
const ProductSubVariation = require("../../models/ProductSubVariation");
const { formatEncodeDate } = require("../../helpers/common");
const Logistics = require("../../models/Logistics");
const Drivers = require("../../models/Drivers");
const {
  sellerProductImageBuilder,
  sellerImageBuilder,
} = require("../../helpers/image-src-builder");
const ProductImages = require("../../models/ProductImages");
const {
  buildSellerReviews,
  buildProductReviews,
} = require("./productReviews.controller");

const orderStatuses = [
  "All",
  "Pending",
  "Denied",
  "Received",
  "Delivered",
  "Cancelled",
  "Release Order - Expired",
  "Release Order - Delivery",
  "Release Order - Customer Pickup",
  "Verified",
  "For Preparation",
  "For Delivery",
  "For Delivery - Warehouse",
  "To Pay",
];

exports.postGetOrderHistoryPaginate = async (req, res, next) => {
  try {
    const {
      query,
      statusFilter = null,
      withDetail = false,
      pageNumber = 1,
      pageSize = 20,
    } = req.body;
    const { customerId } = req;

    if (!orderStatuses.includes(statusFilter))
      return res
        .status(200)
        .json({ success: false, message: "Invalid status filter." });

    let statusQuery = statusFilter;

    const whereClause = {
      customer_id: customerId,
      status: statusQuery,
    };
    if (statusFilter === "All") {
      whereClause.status = { [Op.not]: "Bad Order" };
    }

    if (query) {
      const searchPattern = { [Op.like]: `%${query}%` };
      whereClause[Op.or] = [
        { reference_no: searchPattern },
        { name: searchPattern },
        { payment_method: searchPattern },
        { shipping_type: searchPattern },
      ];
    }

    const offset = (pageNumber - 1) * pageSize;

    let queryResult = null;

    if (withDetail) {
      queryResult = await OrderForm.findAndCountAll({
        where: whereClause,
        include: [
          {
            model: OrderFormDetails,
            as: "order_form_details",
            include: [
              {
                model: Products,
                as: "product",
                include: [
                  {
                    model: ProductVariation,
                    as: "product_variations",
                    attributes: {
                      exclude: ["product_id"],
                    },
                    include: [
                      {
                        model: ProductSubVariation,
                        as: "ProductSubVariations",
                        required: false,
                        attributes: {
                          exclude: ["product_variation_id"],
                        },
                      },
                    ],
                  },
                  {
                    model: ProductImages,
                    as: "product_images",
                  },
                ],
              },
            ],
          },
          {
            model: Logistics,
            as: "logistic",
          },
          {
            model: SellerCompany,
            as: "sellers_company_details",
          },
        ],
        limit: pageSize,
        offset,
        order: [["date_created", "DESC"]],
      });
    } else {
      queryResult = await OrderForm.findAndCountAll({
        where: whereClause,
        limit: pageSize,
        offset,
        order: [["date_created", "DESC"]],
      });
    }

    let response = [];

    const _queryResult = queryResult.rows;
    const _queryCount = queryResult.count;
    if (_queryResult && Array.isArray(_queryResult)) {
      for (const queryR of _queryResult) {
        if (withDetail) {
          const timestamps = {
            dateTimeVerified: queryR.dateTime_verified
              ? formatEncodeDate(queryR.dateTime_verified, false)
              : null,
            dateTimePreparation: queryR.dateTime_for_preparation
              ? formatEncodeDate(queryR.dateTime_for_preparation, false)
              : null,
            dateTimeDelivery: queryR.dateTime_for_delivery
              ? formatEncodeDate(queryR.dateTime_for_delivery, false)
              : null,
            dateDelivered: queryR.date_delivered
              ? formatEncodeDate(queryR.date_delivered, false)
              : null,
            dateOrdered: queryR.date_created
              ? formatEncodeDate(queryR.date_created, false)
              : null,
          };

          const logisticDetail = {
            company: queryR.logistic?.company_name || null,
          };

          const sellerReviews = await buildSellerReviews(
            queryR?.sellers_company_details?.id
          );

          let sellerName = "";
          if (queryR && queryR.sellers_company_details) {
            const companyDetails = queryR.sellers_company_details;
            if (
              companyDetails &&
              companyDetails.shop_name &&
              companyDetails.shop_name !== ""
            ) {
              sellerName = companyDetails.shop_name;
            }
            if (
              companyDetails &&
              companyDetails.company_name &&
              companyDetails.company_name !== ""
            ) {
              sellerName = companyDetails.company_name;
            }
          }
          const sellerDetail = {
            company: sellerName,
            image: queryR?.sellers_company_details?.seller_banner_image
              ? sellerImageBuilder(
                  queryR?.sellers_company_details?.seller_banner_image
                )
              : null,
            reviews: sellerReviews,
          };

          const productDetail = [];

          if (
            queryR.order_form_details &&
            Array.isArray(queryR.order_form_details)
          ) {
            for (const orderDetail of queryR.order_form_details) {
              const { price, quantity, product } = orderDetail;

              let productImage = "";
              const productImages = [];

              const itemReview = await buildProductReviews([product?.id]);
              if (
                product.product_images &&
                Array.isArray(product.product_images) &&
                product.product_images.length > 0
              ) {
                for (const image of product.product_images) {
                  const i = {
                    id: image && image.id ? image.id : 0,
                    url: sellerProductImageBuilder(image.file_name, true),
                    is_thumbnail: image.is_thumbnail,
                  };

                  productImages.push(i);
                }
              }

              if (product.photo === null || product.photo === "") {
                const mainImage = productImages.find((p) => p.is_thumbnail);

                if (mainImage) {
                  productImage = mainImage.url;
                }
              } else {
                productImage = sellerProductImageBuilder(
                  product.photo,
                  product.seller_dashboard_src
                );
              }
              productDetail.push({
                id: product && product.id ? product.id : 0,
                name: product.menu,
                price,
                quantity,
                image: productImage ? productImage : null,
                reviews: itemReview,
              });
            }
          }

          const mainDetail = {
            id: queryR && queryR.id ? queryR.id : 0,
            reference_no: queryR.reference_no,
            payment_method: queryR.payment_method,
            receiver: queryR.name,
            delivery_location: queryR.address,
            total_amount: queryR.total_amount,
            voucher_amount: queryR.voucher_amount,
            status: queryR.status,
            timestamps,
            logisticDetail,
            sellerDetail,
            productDetail,
          };

          response.push(mainDetail);
        } else {
          const mainDetail = {
            id: queryR && queryR.id ? queryR.id : 0,
            reference_no: queryR.reference_no,
            payment_method: queryR.payment_method,
            receiver: queryR.name,
            delivery_location: queryR.address,
            total_amount: queryR.total_amount,
            voucher_amount: queryR.voucher_amount,
            status: queryR.status,
          };
          response.push(mainDetail);
        }
      }
    }
    res.status(200).json({
      success: true,
      response,
      pagination: {
        pageNumber,
        pageSize,
        count: _queryCount,
        totalPages: Math.ceil(_queryCount / pageSize),
      },
    });
  } catch (err) {
    next(err);
  }
};
