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

// ==================== CREATE ROUTES ====================

router.post("/create", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Create GRN from vehicle exit'
    #swagger.description = 'Creates a new Goods Receipt Note from vehicle exit data'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['body'] = {
      in: 'body',
      required: true,
      schema: {
        grnNumber: "GRN-2024-001",
        poId: 1,
        poNumber: "PO-2024-001",
        vendorName: "ABC Suppliers",
        gateEntryNo: "GE-001",
        invoiceNo: "INV-001",
        deliveryChallanNo: "DC-001",
        vehicleId: 1,
        createdBy: 1
      }
    }
    #swagger.responses[201] = {
      description: 'GRN created successfully',
      schema: { success: true, message: "GRN created successfully", data: { id: 1, grn_number: "GRN-2024-001" } }
    }
    #swagger.responses[400] = { description: 'Missing required fields' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.createGrn(req, res);
});

router.post("/manual/create", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Create manual GRN without vehicle/PO'
    #swagger.description = 'Creates a manual Goods Receipt Note without linking to PO or vehicle'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['body'] = {
      in: 'body',
      required: true,
      schema: {
        grn_number: "GRN-MANUAL-001",
        grn_date: "2024-01-15",
        vendor_name: "ABC Suppliers",
        po_number: "PO-2024-001",
        invoice_no: "INV-001",
        delivery_challan_no: "DC-001",
        gate_entry_no: "GE-001",
        remarks: "Manual entry",
        items: [
          {
            item_name: "Product Name",
            ordered_qty: 100,
            received_qty: 100,
            accepted_qty: 95,
            rejected_qty: 5,
            unit_price: 10.50,
            rejected_unit_price: 5.00,
            store_location: "Main Store"
          }
        ]
      }
    }
    #swagger.responses[201] = { description: 'Manual GRN created successfully' }
    #swagger.responses[400] = { description: 'Validation error' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.createManualGrn(req, res);
});

// ==================== READ ROUTES (Specific routes FIRST) ====================

router.get("/approval-counts", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Get approval counts for multiple GRNs'
    #swagger.description = 'Returns approval progress counts for multiple GRNs in a single request'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['grnIds'] = {
      in: 'query',
      type: 'string',
      required: true,
      description: 'Comma-separated GRN IDs (e.g., "1,2,3")'
    }
    #swagger.responses[200] = {
      description: 'Approval counts retrieved',
      schema: {
        success: true,
        data: {
          "1": { approved: 1, rejected: 0, total: 3, current_step: 2, status: "pending" },
          "2": { approved: 3, rejected: 0, total: 3, current_step: 4, status: "approved" }
        },
        workflowTotalApprovers: 3
      }
    }
    #swagger.responses[401] = { description: 'Unauthorized' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.getGrnApprovalCounts(req, res);
});

router.get("/all", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Get all GRNs without pagination'
    #swagger.description = 'Returns all GRNs without pagination limits'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.responses[200] = {
      description: 'GRNs retrieved',
      schema: {
        success: true,
        data: [
          { id: 1, grn_number: "GRN-001", grn_date: "2024-01-15", po_number: "PO-001", vendor_name: "ABC", grn_status: "pending" }
        ]
      }
    }
    #swagger.responses[401] = { description: 'Unauthorized' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.getAllGrnsWithoutPagination(req, res);
});

router.get("/summary/stats", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Get GRN summary statistics'
    #swagger.description = 'Returns summary statistics for GRNs (total, pending, approved, rejected)'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.responses[200] = {
      description: 'Statistics retrieved',
      schema: {
        success: true,
        data: {
          total: 100,
          pending: 30,
          approved: 60,
          rejected: 10,
          totalItems: 500,
          totalValue: 1000000
        }
      }
    }
    #swagger.responses[401] = { description: 'Unauthorized' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.getGrnSummary(req, res);
});

router.get("/vehicle/:vehicleId", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Get GRN by vehicle ID'
    #swagger.description = 'Returns the latest GRN for a specific vehicle'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['vehicleId'] = {
      in: 'path',
      type: 'integer',
      required: true,
      description: 'Vehicle ID'
    }
    #swagger.responses[200] = {
      description: 'GRN retrieved',
      schema: { success: true, data: { id: 1, grn_number: "GRN-001", vehicle_number: "TN01AB1234" } }
    }
    #swagger.responses[404] = { description: 'GRN not found' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.getGrnByVehicleId(req, res);
});

router.get("/number/:grnNumber", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Get GRN by GRN number'
    #swagger.description = 'Returns GRN details by its unique GRN number'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['grnNumber'] = {
      in: 'path',
      type: 'string',
      required: true,
      description: 'GRN number (e.g., GRN-2024-001)'
    }
    #swagger.responses[200] = {
      description: 'GRN retrieved',
      schema: { success: true, data: { id: 1, grn_number: "GRN-001", vendor_name: "ABC" } }
    }
    #swagger.responses[404] = { description: 'GRN not found' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.getGrnByGrnNumber(req, res);
});

router.get("/by-po/:poId", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Get GRNs by PO ID'
    #swagger.description = 'Returns all GRNs associated with a specific Purchase Order'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['poId'] = {
      in: 'path',
      type: 'integer',
      required: true,
      description: 'Purchase Order ID'
    }
    #swagger.responses[200] = {
      description: 'GRNs retrieved',
      schema: {
        success: true,
        data: [
          { id: 1, grn_number: "GRN-001", grn_date: "2024-01-15", items: [] }
        ]
      }
    }
    #swagger.responses[404] = { description: 'No GRNs found' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.getGrnsByPoId(req, res);
});

router.get("/:id/download-pdf", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Download GRN as PDF'
    #swagger.description = 'Generates and downloads a PDF version of the GRN'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['id'] = {
      in: 'path',
      type: 'integer',
      required: true,
      description: 'GRN ID'
    }
    #swagger.responses[200] = {
      description: 'PDF generated successfully',
      schema: { type: 'file' }
    }
    #swagger.responses[404] = { description: 'GRN not found' }
    #swagger.responses[500] = { description: 'PDF generation failed' }
  */
  grnController.downloadGrnPdf(req, res);
});

router.get("/", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Get all GRNs with pagination'
    #swagger.description = 'Returns paginated list of GRNs with search and filter options'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['page'] = {
      in: 'query',
      type: 'integer',
      required: false,
      description: 'Page number (default: 1)'
    }
    #swagger.parameters['limit'] = {
      in: 'query',
      type: 'integer',
      required: false,
      description: 'Items per page (default: 10)'
    }
    #swagger.parameters['search'] = {
      in: 'query',
      type: 'string',
      required: false,
      description: 'Search term for GRN number, PO number, or vendor name'
    }
    #swagger.parameters['status'] = {
      in: 'query',
      type: 'string',
      required: false,
      description: 'Filter by status (pending, approved, rejected)'
    }
    #swagger.responses[200] = {
      description: 'GRNs retrieved',
      schema: {
        success: true,
        data: [],
        pagination: { total: 100, page: 1, limit: 10, totalPages: 10 }
      }
    }
    #swagger.responses[401] = { description: 'Unauthorized' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.getAllGrns(req, res);
});

router.get("/:id", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Get GRN by ID'
    #swagger.description = 'Returns complete GRN details including items and vendor information'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['id'] = {
      in: 'path',
      type: 'integer',
      required: true,
      description: 'GRN ID'
    }
    #swagger.responses[200] = {
      description: 'GRN retrieved',
      schema: {
        success: true,
        data: {
          id: 1,
          grn_number: "GRN-001",
          grn_date: "2024-01-15",
          vendor_name: "ABC Suppliers",
          items: []
        }
      }
    }
    #swagger.responses[404] = { description: 'GRN not found' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.getGrnById(req, res);
});

// ==================== UPDATE ROUTES ====================

router.put("/:grnId/details", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Update GRN details'
    #swagger.description = 'Updates PO reference, invoice number, delivery challan, gate entry, and vehicle'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['grnId'] = {
      in: 'path',
      type: 'integer',
      required: true,
      description: 'GRN ID'
    }
    #swagger.parameters['body'] = {
      in: 'body',
      required: true,
      schema: {
        po_number: "PO-2024-001",
        invoice_no: "INV-001",
        delivery_challan_no: "DC-001",
        gate_entry_no: "GE-001",
        vehicle_id: 1
      }
    }
    #swagger.responses[200] = { description: 'GRN details updated successfully' }
    #swagger.responses[404] = { description: 'GRN not found' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.updateGrnDetails(req, res);
});

router.put("/:grnId/header", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Update GRN header'
    #swagger.description = 'Updates remarks, invoice number, and delivery challan number'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['grnId'] = {
      in: 'path',
      type: 'integer',
      required: true,
      description: 'GRN ID'
    }
    #swagger.parameters['body'] = {
      in: 'body',
      required: true,
      schema: {
        remarks: "Updated remarks",
        invoice_no: "INV-002",
        delivery_challan_no: "DC-002"
      }
    }
    #swagger.responses[200] = { description: 'GRN header updated successfully' }
    #swagger.responses[404] = { description: 'GRN not found' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.updateGrnHeader(req, res);
});

router.put("/:grnId/items/batch", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Update multiple GRN items (batch)'
    #swagger.description = 'Updates multiple GRN items in a single request'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['grnId'] = {
      in: 'path',
      type: 'integer',
      required: true,
      description: 'GRN ID'
    }
    #swagger.parameters['body'] = {
      in: 'body',
      required: true,
      schema: {
        items: [
          {
            id: 1,
            ordered_qty: 100,
            received_qty: 100,
            accepted_qty: 95,
            rejected_qty: 5,
            unit_price: 10.50,
            rejected_unit_price: 5.00,
            batch_number: "BATCH-001",
            mfg_date: "2024-01-01",
            expiry_date: "2025-01-01",
            seal_number: "SEAL-001",
            store_location: "Main Store"
          }
        ]
      }
    }
    #swagger.responses[200] = { description: 'Items updated successfully' }
    #swagger.responses[404] = { description: 'GRN not found' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.updateGrnItems(req, res);
});

router.put("/:grnId/items/:itemId", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Update single GRN item'
    #swagger.description = 'Updates a single GRN item by ID'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['grnId'] = {
      in: 'path',
      type: 'integer',
      required: true,
      description: 'GRN ID'
    }
    #swagger.parameters['itemId'] = {
      in: 'path',
      type: 'integer',
      required: true,
      description: 'GRN Item ID'
    }
    #swagger.parameters['body'] = {
      in: 'body',
      required: true,
      schema: {
        accepted_qty: 95,
        rejected_qty: 5,
        unit_price: 10.50,
        store_location: "Main Store"
      }
    }
    #swagger.responses[200] = { description: 'Item updated successfully' }
    #swagger.responses[404] = { description: 'Item not found' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.updateGrnItem(req, res);
});

router.put("/:grnId/complete", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Complete GRN'
    #swagger.description = 'Marks a GRN as completed'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['grnId'] = {
      in: 'path',
      type: 'integer',
      required: true,
      description: 'GRN ID'
    }
    #swagger.responses[200] = { description: 'GRN completed successfully' }
    #swagger.responses[404] = { description: 'GRN not found' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.completeGrn(req, res);
});

router.put("/:id/approve", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Approve GRN'
    #swagger.description = 'Approves a GRN (updates status to Approved)'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['id'] = {
      in: 'path',
      type: 'integer',
      required: true,
      description: 'GRN ID'
    }
    #swagger.responses[200] = { description: 'GRN approved successfully' }
    #swagger.responses[400] = { description: 'GRN already approved' }
    #swagger.responses[404] = { description: 'GRN not found' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.approveGrn(req, res);
});

// ==================== DELETE ROUTES ====================

router.delete("/:grnId/items/:itemId", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Delete GRN item'
    #swagger.description = 'Deletes a specific item from a GRN'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['grnId'] = {
      in: 'path',
      type: 'integer',
      required: true,
      description: 'GRN ID'
    }
    #swagger.parameters['itemId'] = {
      in: 'path',
      type: 'integer',
      required: true,
      description: 'GRN Item ID'
    }
    #swagger.responses[200] = { description: 'Item deleted successfully' }
    #swagger.responses[404] = { description: 'Item not found' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.deleteGrnItem(req, res);
});

router.delete("/hard/:id", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Hard delete GRN (permanent)'
    #swagger.description = 'Permanently deletes a GRN from the database'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['id'] = {
      in: 'path',
      type: 'integer',
      required: true,
      description: 'GRN ID'
    }
    #swagger.responses[200] = { description: 'GRN permanently deleted' }
    #swagger.responses[404] = { description: 'GRN not found' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.hardDeleteGrn(req, res);
});

router.delete("/:id", authenticate, (req, res) => {
  /*
    #swagger.tags = ['GRN']
    #swagger.summary = 'Soft delete GRN'
    #swagger.description = 'Soft deletes a GRN (sets is_deleted flag to true)'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['id'] = {
      in: 'path',
      type: 'integer',
      required: true,
      description: 'GRN ID'
    }
    #swagger.responses[200] = { description: 'GRN deleted successfully' }
    #swagger.responses[404] = { description: 'GRN not found' }
    #swagger.responses[500] = { description: 'Server error' }
  */
  grnController.deleteGrn(req, res);
});

module.exports = router;