const express = require("express");
const router = express.Router();
const multer = require("multer");
const purchaseInvoiceController = require("../../controllers/procurement/purchaseInvoiceController");
const authenticate = require("../../middlewares/authenticate");

// Configure multer for memory storage
const storage = multer.memoryStorage();
const upload = multer({
  storage: storage,
  limits: { fileSize: 5 * 1024 * 1024 }, // 5MB limit
  fileFilter: (req, file, cb) => {
    const allowedTypes = ['application/pdf', 'image/jpeg', 'image/png', 'image/jpg'];
    if (allowedTypes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error('Only PDF, JPG, and PNG files are allowed'), false);
    }
  }
});

// ==================== CREATE ====================

router.post("/create-from-grn", authenticate, upload.single("invoice_file"), (req, res) => {
  /*
    #swagger.tags = ['Purchase Invoices']
    #swagger.summary = 'Create purchase invoice from GRN'
    #swagger.security = [{ "bearerAuth": [] }]
  */
  purchaseInvoiceController.createPurchaseInvoiceFromGRN(req, res);
});

// ==================== GET ====================

router.get("/", authenticate, (req, res) => {
  /*
    #swagger.tags = ['Purchase Invoices']
    #swagger.summary = 'Get all purchase invoices with pagination'
    #swagger.security = [{ "bearerAuth": [] }]
  */
  purchaseInvoiceController.getAllPurchaseInvoices(req, res);
});

router.get("/:id", authenticate, (req, res) => {
  /*
    #swagger.tags = ['Purchase Invoices']
    #swagger.summary = 'Get purchase invoice by ID'
    #swagger.security = [{ "bearerAuth": [] }]
  */
  purchaseInvoiceController.getPurchaseInvoiceById(req, res);
});

// Accept both PUT and PATCH for flexibility
router.put("/:id/approve", authenticate, (req, res) => {
  purchaseInvoiceController.approvePurchaseInvoice(req, res);
});

router.patch("/:id/approve", authenticate, (req, res) => {
  purchaseInvoiceController.approvePurchaseInvoice(req, res);
});

// ==================== DELETE ====================

router.delete("/:id", authenticate, (req, res) => {
  /*
    #swagger.tags = ['Purchase Invoices']
    #swagger.summary = 'Delete purchase invoice (soft delete)'
    #swagger.security = [{ "bearerAuth": [] }]
  */
  purchaseInvoiceController.deletePurchaseInvoice(req, res);
});

module.exports = router;