const OrderList = require("../models/OrderList");
const Customers = require("../models/Customers");
const Seller = require("../models/Seller");
const OrderFormDetails = require("../models/OrderFormDetails");
const Products = require("../models/Products");
const DetailProductReviews = require("../models/ProductRating");
const ProductVariation = require("../models/ProductVariation");
const ProductSubVariation = require("../models/ProductSubVariation");
const SellersCompany = require("../models/SellersCompany");
const Drivers = require("../models/Drivers");
const Trucks = require("../models/Trucks");
const LogisticsCompany = require("../models/Logistics");
const { Op } = require("sequelize");
const { formatEncodeDate } = require("../helpers/common");

exports.findAllOrders = async (req, res, next) => {
  const { customerId } = req;
  const { filter } = req.query;

  async function checkIfAgent(customerId) {
    try {
      const customerDetail = await Customers.findByPk(customerId);
      const { type, agent_code } = customerDetail;
      const accountTypeAgent = type === "Agent";
      return { accountTypeAgent, agent_code };
    } catch (err) {
      next(err);
    }
  }

  const agentDetails = await checkIfAgent(customerId);
  const { accountTypeAgent: isAgent, agent_code } = agentDetails;

  const whereClause = {
    [Op.or]: [{ customer_id: customerId }, isAgent && { agentCode: agent_code }],
    ...(filter
      ? filter === "Fulfilled"
        ? { status: { [Op.or]: ["Delivered", "Received"] } }
        : { status: filter }
      : {}),
  };

  OrderList.findAll({
    where: whereClause,
    include: [
      {
        model: Customers,
        as: "customer",
      },
      {
        model: SellersCompany,
        as: "seller",
      },
    ],
  })
    .then((orderList) => {
      const orderDetailsPromises = orderList.map((orderLists) => {
        const customer = orderLists.customer;
        const seller = orderLists.seller;

        return OrderFormDetails.findAll({
          where: {
            order_form_id: orderLists.id,
          },
          include: [
            {
              model: Products,
              as: "product",
            },
            {
              model: ProductVariation,
              as: "variation",
            },
            {
              model: ProductSubVariation,
              as: "sub_variation",
            },
          ],
        }).then((orderFormDetails) => {
          const productDetailsPromises = orderFormDetails.map((orderFormDetail) => {
            return DetailProductReviews.findAll({
              where: {
                product_id: orderFormDetail.product_id,
                customer_id: customerId,
                order_form_id: orderFormDetail.id,
              },
            }).then((reviews) => ({
              id: orderFormDetail.product_id,
              image:
                orderFormDetail.product && orderFormDetail.product.photo
                  ? `https://buildhub.ph/img/products/${orderFormDetail.product.photo}`
                  : null,
              name: orderFormDetail.product?.menu || null,
              sku: orderFormDetail.product?.sku || null,
              price: orderFormDetail.price,
              quantity: orderFormDetail.quantity,
              amount: orderFormDetail.amount,
              variation: orderFormDetail.variation
                ? {
                    id: orderFormDetail.variation.id,
                    name: orderFormDetail.variation.variation,
                    description: orderFormDetail.variation.description,
                    price: orderFormDetail.variation.price,
                    discountedPrice: orderFormDetail.variation ? orderFormDetail.variation.discounted_price : null,
                  }
                : null,
              subVariation: orderFormDetail.sub_variation
                ? {
                    id: orderFormDetail.sub_variation.id,
                    name: orderFormDetail.sub_variation.custom,
                    description: orderFormDetail.sub_variation.description,
                    price: orderFormDetail.sub_variation.price,
                    discountedPrice: orderFormDetail.sub_variation
                      ? orderFormDetail.sub_variation.discounted_price
                      : null,
                  }
                : null,
              status: orderFormDetail.status,
              isRated: orderFormDetail.rated,
              reviews: reviews.map((review) => ({
                rate: review.rate,
                reviews: review.reviews,
                timestamp: formatEncodeDate(review.timestamp, true),
              })),
            }));
          });

          return Promise.all(productDetailsPromises).then((productDetails) => ({
            orderFormId: orderLists.id,
            referenceNo: orderLists.reference_no,
            encodeDate: formatEncodeDate(orderLists.encode_date),
            seller: seller
              ? {
                  id: seller.seller_id,
                  name: seller.shop_name !== "" || seller.shop_name !== null ? seller.shop_name : seller.company_name,
                  logo: seller && seller.seller_logo ? `https://buildhub.ph/img/seller/${seller.seller_logo}` : null,
                }
              : null,
            customer: customer
              ? {
                  id: customer.id,
                  firstName: customer.first_name,
                  lastName: customer.last_name,
                  email_address: customer.email,
                  phoneNo: customer.phone,
                }
              : null,
            status: orderLists.status,
            remarks: orderLists.remarks,
            paymentMethod: orderLists.payment_method,
            shipping: {
              type: orderLists.shipping_type,
              fee: orderLists.delivery_fee,
            },
            location: orderLists.address,
            dateTimeVerified: formatEncodeDate(orderLists.dateTime_verified, true),
            dateTimePreparation: formatEncodeDate(orderLists.dateTime_for_preparation, true),
            dateTimeDelivery: formatEncodeDate(orderLists.dateTime_for_delivery, true),
            dateDelivered: formatEncodeDate(orderLists.date_delivered, true),
            fulfilled: formatEncodeDate(orderLists.dateTime_for_preparation, true),
            deliveryTrackingNo: orderLists.reference_no,
            productDetails,
          }));
        });
      });

      Promise.all(orderDetailsPromises)
        .then((orderDetails) => {
          res.status(200).json({ success: true, orderDetails });
        })
        .catch((err) => {
          next(err);
        });
    })
    .catch((err) => {
      next(err);
    });
};

exports.findOrderByReferenceNo = (req, res, next) => {
  //   const { customerId } = req;
  const { referenceNo } = req.params;

  OrderList.findAll({
    where: {
      //   customer_id: customerId,
      reference_no: referenceNo,
    },
    include: [
      {
        model: Customers,
        as: "customer",
      },
      {
        model: SellersCompany,
        as: "seller",
      },
      {
        model: Drivers,
        as: "driver_detail",
      },
      {
        model: Trucks,
        as: "truck_detail",
      },
      {
        model: LogisticsCompany,
        as: "logistics_detail",
      },
    ],
  })
    .then((orderList) => {
      const orderDetailsPromises = orderList.map((orderLists) => {
        const customer = orderLists.customer;
        const seller = orderLists.seller;

        return OrderFormDetails.findAll({
          where: {
            order_form_id: orderLists.id,
          },
          include: [
            {
              model: Products,
              as: "product",
            },
            {
              model: ProductVariation,
              as: "variation",
            },
            {
              model: ProductSubVariation,
              as: "sub_variation",
            },
          ],
        }).then((orderFormDetails) => {
          const productDetailsPromises = orderFormDetails.map((orderFormDetail) => {
            return DetailProductReviews.findAll({
              where: {
                product_id: orderFormDetail.product_id,
                //   customer_id: customerId,
                order_form_id: orderFormDetail.id,
              },
            }).then((reviews) => ({
              id: orderFormDetail.product_id,
              image:
                orderFormDetail.product && orderFormDetail.product.photo
                  ? `https://buildhub.ph/img/products/${orderFormDetail.product.photo}`
                  : null,
              name: orderFormDetail.product?.menu || null,
              sku: orderFormDetail.product?.sku || null,
              price: orderFormDetail.price,
              quantity: orderFormDetail.quantity,
              amount: orderFormDetail.amount,
              variation: orderFormDetail.variation
                ? {
                    id: orderFormDetail.variation.id,
                    name: orderFormDetail.variation.variation,
                    description: orderFormDetail.variation.description,
                    price: orderFormDetail.variation.price,
                    discountedPrice: orderFormDetail.variation ? orderFormDetail.variation.discounted_price : null,
                  }
                : null,
              subVariation: orderFormDetail.sub_variation
                ? {
                    id: orderFormDetail.sub_variation.id,
                    name: orderFormDetail.sub_variation.custom,
                    description: orderFormDetail.sub_variation.description,
                    price: orderFormDetail.sub_variation.price,
                    discountedPrice: orderFormDetail.sub_variation
                      ? orderFormDetail.sub_variation.discounted_price
                      : null,
                  }
                : null,
              status: orderFormDetail.status,
              isRated: orderFormDetail.isRated,
              reviews: reviews.map((review) => ({
                rate: review.rate,
                reviews: review.reviews,
                timestamp: formatEncodeDate(review.timestamp, true),
              })),
            }));
          });

          return Promise.all(productDetailsPromises).then((productDetails) => ({
            orderFormId: orderLists.id,
            referenceNo: orderLists.reference_no,
            encodeDate: orderLists.encode_date ? formatEncodeDate(orderLists.encode_date) : null,
            seller: seller
              ? {
                  id: seller.seller_id,
                  name: seller.shop_name !== "" || seller.shop_name !== null ? seller.shop_name : seller.company_name,
                  logo: seller && seller.seller_logo ? `https://buildhub.ph/img/seller/${seller.seller_logo}` : null,
                }
              : null,
            customer: customer
              ? {
                  id: customer.id,
                  firstName: customer.first_name,
                  lastName: customer.last_name,
                  email_address: customer.email,
                  phoneNo: customer.phone,
                }
              : null,
            status: orderLists.status,
            remarks: orderLists.remarks,
            paymentMethod: orderLists.payment_method,
            shipping: {
              type: orderLists.shipping_type,
              fee: orderLists.delivery_fee,
            },
            total_amount: orderLists.total_amount,
            voucher_amount: orderLists.voucher_amount,
            logistics_detail: {
              driver: orderLists.driver_detail?.name,
              logistics: orderLists.logistics_detail?.company_name,
              truck: {
                plate: orderLists.truck_detail?.truck_plate_no,
                type: orderLists.truck_detail?.truck_type,
              },
            },
            location: orderLists.address,
            dateTimeVerified: orderLists.dateTime_verified
              ? formatEncodeDate(orderLists.dateTime_verified, true)
              : null,
            dateTimePreparation: orderLists.dateTime_for_preparation
              ? formatEncodeDate(orderLists.dateTime_for_preparation, true)
              : null,
            dateTimeDelivery: orderLists.dateTime_for_delivery
              ? formatEncodeDate(orderLists.dateTime_for_delivery, true)
              : null,
            dateDelivered: orderLists.date_delivered ? formatEncodeDate(orderLists.date_delivered, true) : null,
            fulfilled: orderLists.dateTime_for_preparation
              ? formatEncodeDate(orderLists.dateTime_for_preparation, true)
              : null,
            deliveryTrackingNo: orderLists.reference_no,
            productDetails,
          }));
        });
      });

      Promise.all(orderDetailsPromises)
        .then((orderDetails) => {
          res.status(200).json({ success: true, orderDetails });
        })
        .catch((err) => {
          next(err);
        });
    })
    .catch((err) => {
      next(err);
    });
};
