const express = require("express");
const router = express.Router();
const uploadProformaController = require("../../controllers/procurement/uploadProformaController");
const authenticate = require("../../middlewares/authenticate");
const multer = require("multer");
const path = require("path");
const fs = require("fs");
const crypto = require("crypto");

// Helper function to ensure directory exists
const ensureDir = (dir) => {
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
    }
};

// Configure multer for file uploads with year/month folder structure
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        const baseDir = path.join(__dirname, "../../uploads/Proforma");
        const now = new Date();
        const year = now.getFullYear().toString();
        const month = (now.getMonth() + 1).toString().padStart(2, "0");
        const finalDir = path.join(baseDir, year, month);
        ensureDir(finalDir);
        cb(null, finalDir);
    },
    filename: function (req, file, cb) {
        const ext = path.extname(file.originalname);
        const timestamp = Date.now();
        const randomStr = crypto.randomBytes(4).toString("hex");
        const poNumber = req.body.po_number || "unknown";
        const cleanPONumber = poNumber.replace(/[^a-zA-Z0-9]/g, '-');
        const filename = `Proforma_${cleanPONumber}_${timestamp}_${randomStr}${ext}`;
        cb(null, filename);
    }
});

const fileFilter = (req, file, cb) => {
    const allowedMimeTypes = [
        "image/jpeg", "image/png", "image/gif", "image/jpg",
        "application/pdf", "application/msword",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "application/vnd.ms-excel",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "text/plain"
    ];
    
    const allowedExtensions = ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.jpg', '.jpeg', '.png', '.txt'];
    const ext = path.extname(file.originalname).toLowerCase();
    const isExtAllowed = allowedExtensions.includes(ext);
    const isMimeAllowed = allowedMimeTypes.includes(file.mimetype);
    
    if (isMimeAllowed && isExtAllowed) {
        cb(null, true);
    } else {
        cb(new Error("Only .pdf, .doc, .docx, .xls, .xlsx, .jpg, .jpeg, .png, .txt files are allowed"), false);
    }
};

const upload = multer({ 
    storage: storage,
    fileFilter: fileFilter,
    limits: { fileSize: 10 * 1024 * 1024 }
});

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

router.get("/po-details/:po_number", authenticate, (req, res) => {
  /*
    #swagger.tags = ['Upload Proforma Postgre']
    #swagger.summary = 'Get PO details (vendor & amount) by PO number'
    #swagger.security = [{ "bearerAuth": [] }]
  */
  uploadProformaController.getPODetailsForProforma(req, res);
});

router.get("/", authenticate, (req, res) => {
  /*
    #swagger.tags = ['Upload Proforma Postgre']
    #swagger.summary = 'Get all upload proforma records'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.parameters['search'] = { in: 'query', type: 'string' }
    #swagger.parameters['page'] = { in: 'query', type: 'integer' }
    #swagger.parameters['limit'] = { in: 'query', type: 'integer' }
  */
  uploadProformaController.getAllUploadProforma(req, res);
});

router.get("/:id", authenticate, (req, res) => {
  /*
    #swagger.tags = ['Upload Proforma Postgre']
    #swagger.summary = 'Get upload proforma by ID'
    #swagger.security = [{ "bearerAuth": [] }]
  */
  uploadProformaController.getUploadProformaById(req, res);
});

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

router.post("/", authenticate, upload.array("files", 10), (req, res) => {
  /*
    #swagger.tags = ['Upload Proforma Postgre']
    #swagger.summary = 'Create upload proforma with files'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.consumes = ['multipart/form-data']
  */
  uploadProformaController.createUploadProforma(req, res);
});

// ==================== UPDATE ====================

router.put("/:id", authenticate, upload.array("files", 10), (req, res) => {
  /*
    #swagger.tags = ['Upload Proforma Postgre']
    #swagger.summary = 'Update upload proforma'
    #swagger.security = [{ "bearerAuth": [] }]
    #swagger.consumes = ['multipart/form-data']
  */
  uploadProformaController.updateUploadProforma(req, res);
});

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

router.delete("/:id", authenticate, (req, res) => {
  /*
    #swagger.tags = ['Upload Proforma Postgre']
    #swagger.summary = 'Soft delete upload proforma'
    #swagger.security = [{ "bearerAuth": [] }]
  */
  uploadProformaController.deleteUploadProforma(req, res);
});

module.exports = router;