const {
  recommendedItemsService,
  saveQuotation,
  getQuotationDetails,
  updateQuotationStatus,
  updateQuotationDetailStatus,
} = require("../helpers/quotation.service");
const ProductMenu = require("../models/ProductMenu");

exports.recommendedItems = async (req, res, next) => {
  try {
    const { customerId } = req;

    const { requestQuotation } = req.body;

    if (!requestQuotation || !Array.isArray(requestQuotation))
      return res.status(400).json({ success: false, message: "Invalid data structure." });

    for (const quotation of requestQuotation) {
      const { category_id, quantity } = quotation;

      if (!category_id || category_id === "" || !quantity || quantity === "")
        return res.status(400).json({ success: false, message: "Invalid category or quantity." });

      const category = await ProductMenu.findByPk(category_id);
      if (!category) return res.status(400).json({ success: false, message: "Invalid category " });
    }

    const { error, quotation: recommendedQuotation } = await recommendedItemsService(customerId, requestQuotation);
    if (error) return res.status(400).json({ success: false, message: error });

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

exports.submitCustomerQuotation = async (req, res, next) => {
  try {
    const { customerId } = req;

    const { requestQuotation } = req.body;

    if (!requestQuotation || !Array.isArray(requestQuotation))
      return res.status(400).json({ success: false, message: "Invalid data structure." });

    for (const quotation of requestQuotation) {
      const { item_name, quantity } = quotation;

      if (!item_name || item_name === "" || !quantity || quantity === "")
        return res.status(400).json({ success: false, message: "Invalid item name or quantity." });
    }
    const { error, quotation } = await saveQuotation(customerId, requestQuotation);
    if (error) return res.status(400).json({ success: false, message: error });

    const quotationTotalAmount = quotation.customer_quotation_details.reduce(
      (acc, value) => acc + parseFloat(value.total_price),
      0
    );

    const responseQuotation = {
      ...(quotation.toJSON ? quotation.toJSON() : quotation),
      total_quotation_price: quotationTotalAmount,
    };

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

exports.getQuotationDetail = async (req, res, next) => {
  try {
    const { customerId } = req;
    const { quotation_id = null, statusFilter = null } = req.query;

    const responseJson = [];
    let quotationDetails = null;
    const availableFilters = ["Customer Request for Quotation", "Customer Review Quotation", "Quotation For Checkout"];

    if (statusFilter) {
      if (!availableFilters.includes(statusFilter)) {
        return res.status(400).json({ success: false, message: "Invalid status filter." });
      }
    }
    if (!quotation_id) {
      quotationDetails = await getQuotationDetails(null, customerId, statusFilter);
    } else {
      quotationDetails = await getQuotationDetails(quotation_id, null, statusFilter);
    }

    if (!quotationDetails) {
      return res.status(400).json({ success: false, message: "No quotations found." });
    }
    if (!quotation_id) {
      for (const quotation of quotationDetails) {
        const quotationTotalAmount = quotation.customer_quotation_details.reduce(
          (acc, value) => acc + parseFloat(value.total_price),
          0
        );

        const responseQuotation = {
          ...(quotation.toJSON ? quotation.toJSON() : quotation),
          total_quotation_price: quotationTotalAmount,
        };

        responseJson.push(responseQuotation);
      }
    } else {
      const quotationTotalAmount = quotationDetails.customer_quotation_details.reduce(
        (acc, value) => acc + parseFloat(value.total_price),
        0
      );

      const responseQuotation = {
        ...(quotationDetails.toJSON ? quotationDetails.toJSON() : quotationDetails),
        total_quotation_price: quotationTotalAmount,
      };
      responseJson.push(responseQuotation);
    }

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

exports.acceptOrDenyQuotation = async (req, res, next) => {
  try {
    const { customerId } = req;
    const { quotation_id, accept = true } = req.body;

    const quotationDetail = await getQuotationDetails(quotation_id, null, "Customer Review Quotation");
    if (!quotationDetail) return res.status(400).json({ success: false, message: "No quotations found." });

    const { error, quotation } = await updateQuotationStatus(quotation_id, accept);

    if (error) {
      return res.status(400).json({ success: false, message: error });
    }

    res.status(200).json({ success: true, quotation });
  } catch (err) {
    next(err);
  }
};
exports.acceptOrDenyQuotationDetail = async (req, res, next) => {
  try {
    const { customerId } = req;
    const { quotation_id, quotation_detail_id, accept = true } = req.body;

    const quotationDetail = await getQuotationDetails(quotation_id, null, "Customer Review Quotation");
    if (!quotationDetail) return res.status(400).json({ success: false, message: "No quotations found." });

    const { error, quotation } = await updateQuotationDetailStatus(quotation_detail_id, accept);

    if (error) {
      return res.status(400).json({ success: false, message: error });
    }

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