const emailBuilder = require("../../helpers/transporter");
const OrderForm = require("../../models/OrderForm");
const OrderFormDetails = require("../../models/OrderFormDetails");
const Product = require("../../models/Products");
const Voucher = require("../../models/Vouchers");
const SellersCompany = require("../../models/SellersCompany");
const {
  readyForPickupTemplate,
  readyForDeliveryTemplate,
  preparingOrdersTemplate,
  orderReadyTemplate,
} = require("../../helpers/email-templates/html-bodys-new");

exports.releaseOrderMailer = async (req, res, next) => {
  const { reference_no, customer_name, customer_email, order_status } = req.body;

  try {
    const isPickup = order_status.includes("Pickup");

    const OrderDetail = await OrderForm.findOne({
      where: {
        reference_no,
      },
    });

    if (!OrderDetail) {
      throw new Error("Invalid order reference #.");
    }
    let templateEmail = readyForDeliveryTemplate(OrderDetail.name, reference_no);
    let address = OrderDetail.address;
    if (isPickup) {
      const SellersCompanyDetail = await SellersCompany.findByPk(OrderDetail.seller_id);
      address = SellersCompanyDetail.address;
      templateEmail = readyForPickupTemplate(OrderDetail.name, reference_no);
    }
    const receivers = [customer_email];
    const emailResponse = await emailBuilder(receivers, [], "Buildhub - Order Status Update", true, templateEmail, []);
    res.status(200).json({ success: true, email_details: emailResponse });
  } catch (error) {
    console.error(error);
    next(error);
  }
};

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

  try {
    const orderForm = await OrderForm.findOne({
      where: {
        reference_no,
      },
      attributes: [
        "customer_id",
        "name",
        "reference_no",
        "date_created",
        "voucher_id_used",
        "delivery_fee",
        "total_amount",
        "seller_id",
        "shipping_type",
        "address",
      ],
      include: [
        {
          model: OrderFormDetails,
          as: "order_form_details",
          attributes: ["product_id", "quantity", "discounted_price", "price", "amount"],
          include: [
            {
              model: Product,
              as: "product",
              attributes: ["menu", "photo", "discounted_price", "price"],
            },
          ],
        },
        {
          model: Voucher,
          as: "voucher_details",
          attributes: ["amount", "amount_in_percent"],
          required: false,
        },
        {
          model: SellersCompany,
          as: "sellers_company_details",
          attributes: ["shop_name", "company_name", "address"],
        },
      ],
    });

    if (!orderForm) throw new Error("Order Form not found");

    let voucherAmount = 0;
    if (orderForm.voucher_details) {
      const voucherDetail = orderForm.voucher_details;

      if (voucherDetail.amount_in_percent) {
        const totalAmount = orderForm.total_amount;
        const percent = parseFloat(voucherDetail.amount_in_percent);
        voucherAmount = (totalAmount * percent) / 100;
      } else {
        voucherAmount = parseFloat(voucherDetail.amount);
      }
    }

    const orderSummary = {
      date_created: orderForm.date_created,
      voucher_amount: voucherAmount,
      shipping_fee: orderForm.delivery_fee,
      shipping_type: orderForm.shipping_type,
      total_amount: orderForm.total_amount,
      seller_name:
        orderForm.sellers_company_details.shop_name === "" || orderForm.sellers_company_details.shop_name === null
          ? orderForm.sellers_company_details.company_name
          : orderForm.sellers_company_details.shop_name,
      seller_address: orderForm.sellers_company_details.address,
      customer_address: orderForm.address,
    };

    const productDetails = [];

    for (const orderFormDetail of orderForm.order_form_details) {
      let __productPrice = orderFormDetail.product.price;
      if (orderFormDetail.product.discounted_price && orderFormDetail.product.discounted_price > 0) {
        __productPrice = orderFormDetail.product.discounted_price;
      }

      productDetails.push({
        photo: orderFormDetail.product.photo,
        menu: orderFormDetail.product.menu,
        qty: orderFormDetail.quantity,
        price: __productPrice,
      });
    }
    const receivers = [customer_email];
    const emailResponse = await emailBuilder(
      receivers,
      [],
      "Buildhub - Order Status Update",
      true,
      preparingOrdersTemplate(reference_no, orderSummary, productDetails),
      []
    );

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

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

    const orderForm = await OrderForm.findOne({
      where: {
        reference_no,
      },
      attributes: ["name", "email"],
    });

    if (!orderForm) throw new Error("Order not found.");

    const receivers = [customer_email];
    const emailResponse = await emailBuilder(
      receivers,
      [],
      "Buildhub - Order Status Update",
      true,
      orderReadyTemplate(orderForm.name, reference_no),
      []
    );

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