const { isBase64 } = require("../../helpers/common");
const {
  customerSalesReportService,
  itemSalesReportService,
  generalSalesReportService,
  agentSalesReportService,
  voucherSalesReportService,
} = require("../../services/sales-report.service");

// By Customer
exports.customerSalesReportByWeek = async (req, res, next) => {};

exports.customerSalesReportByMonth = async (req, res, next) => {};

// By Item
exports.itemSalesReportByWeek = async (req, res, next) => {};

exports.itemSalesReportByMonth = async (req, res, next) => {};

// Main
exports.salesReportController = async (req, res, next) => {
  const {
    report = "customer",
    dateStart,
    dateEnd,
    includeBacklog = false,
    voucherCode = "",
  } = req.query;

  let _includeBacklog = false;
  if (includeBacklog == "true") {
    _includeBacklog = true;
  }
  const dateRange = {
    dateStart,
    dateEnd,
  };

  let decodedKeyword = voucherCode;
  if (voucherCode && isBase64(voucherCode)) {
    try {
      decodedKeyword = decodeURIComponent(
        Buffer.from(voucherCode, "base64").toString("utf-8"),
      );
    } catch {
      decodedKeyword = voucherCode;
    }
  }

  let salesReport = "";
  if (report === "customer") {
    salesReport = await customerSalesReportService(dateRange, _includeBacklog);
  } else if (report === "item") {
    salesReport = await itemSalesReportService(dateRange, _includeBacklog);
  } else if (report === "general") {
    salesReport = await generalSalesReportService(dateRange, _includeBacklog);
  } else if (report === "agent") {
    salesReport = await agentSalesReportService(dateRange, _includeBacklog);
  } else if (report === "voucher") {
    salesReport = await voucherSalesReportService(
      dateRange,
      decodedKeyword,
      _includeBacklog,
    );
  }
  if (salesReport.error) {
    return res.status(400).json({ success: false, message: salesReport.error });
  }
  res.setHeader(
    "Content-Type",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  );
  res.setHeader(
    "Content-Disposition",
    `attachment; filename=${salesReport.report.fileName}`,
  );

  res.status(200).send(salesReport.report.buffer);
};

// Sales Report by Month as a Whole
