import type { Request, Response } from "express";
import outstandingReportService from "../services/OutstandingReportService.js";
import { OutstandingReportExcel } from "../utils/excel/OutstandingReportExcel.js";
import { OutstandingReportPdf } from "../utils/pdf/OutstandingReportPdf.js";

export class OutstandingReportController {
  async getReport(req: Request, res: Response) {
    try {
      const type = req.query.type as string; // 'customers' or 'suppliers'
      const page = parseInt(req.query.page as string) || 1;
      const limit = parseInt(req.query.limit as string) || 20;
      const search = (req.query.search as string) || "";

      let data;
      if (type === "suppliers") {
        data = await outstandingReportService.getSuppliers(page, limit, search);
      } else {
        // default to customers
        data = await outstandingReportService.getCustomers(page, limit, search);
      }

      return res.status(200).json({
        status: true,
        message: "Outstanding report fetched successfully",
        data,
      });
    } catch (error: any) {
      return res.status(500).json({
        status: false,
        message: error.message || "Failed to fetch outstanding report",
      });
    }
  }

  async exportExcel(req: Request, res: Response) {
    try {
      const type = (req.query.type as string) === "suppliers" ? "suppliers" : "customers";
      const data = await outstandingReportService.getAllForExport(type);
      await OutstandingReportExcel.export(data, type, res);
    } catch (error: any) {
      if (!res.headersSent) {
        return res.status(500).json({
          status: false,
          message: error.message || "Failed to export outstanding report Excel",
        });
      }
    }
  }

  async exportPdf(req: Request, res: Response) {
    try {
      const type = (req.query.type as string) === "suppliers" ? "suppliers" : "customers";
      const data = await outstandingReportService.getAllForExport(type);
      await OutstandingReportPdf.export(data, type, res);
    } catch (error: any) {
      if (!res.headersSent) {
        return res.status(500).json({
          status: false,
          message: error.message || "Failed to export outstanding report PDF",
        });
      }
    }
  }
}

export default new OutstandingReportController();

