const express = require("express");
const router = express.Router();
const authorize = require("../../../../middlewares/authorize-sapps");
const tenderQuotationService = require("./tenderQuotation.service");
const fs = require('fs');
const path = require('path');
const multer = require('multer');

// Setup multer untuk upload file proposal
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const dest = path.resolve(__dirname, "../../../../public/data/documents/tenderquotations");
    
    // Auto create folder if not exists
    if (!fs.existsSync(dest)) {
      fs.mkdirSync(dest, { recursive: true });
    }
    
    cb(null, dest);
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + "-" + file.originalname);
  },
});

// Middleware upload dengan filter dan batasan ukuran file
const upload = multer({
  storage: storage,
  limits: {
    fileSize: 15 * 1024 * 1024, // maksimal 15MB
  },
  fileFilter: function (req, file, cb) {
    // Izinkan PDF, DOC, DOCX
    const allowedMimes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
    if (allowedMimes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error("Hanya file PDF, DOC, atau DOCX yang diperbolehkan!"));
    }
  },
});

router.post("/", authorize(), getAll);
router.post("/by-tender/:tenderId", authorize(), getByTenderId);
router.post("/by-vendor", authorize(), getByVendorId);
router.post("/create", authorize(), create);
router.put("/:id", authorize(), update);
router.post("/submit", authorize(), submit);
router.post("/upload-files/:tenderquotationId", authorize(), upload.array("files", 10), uploadFiles);
router.delete("/:id", authorize(), _delete);

module.exports = router;

function getAll(req, res, next) {
  tenderQuotationService
    .getAll(req.body)
    .then((result) => res.json(result))
    .catch(next);
}

function getByTenderId(req, res, next) {
  tenderQuotationService
    .getByTenderId(req.params.tenderId)
    .then((result) => res.json(result))
    .catch(next);
}

function getByVendorId(req, res, next) {
  tenderQuotationService
    .getByVendorId(req.body.tendervendor_id, req.body.tender_id)
    .then((result) => res.json(result))
    .catch(next);
}

function create(req, res, next) {
  tenderQuotationService
    .create(req.body)
    .then((result) => res.json(result))
    .catch(next);
}

function update(req, res, next) {
  const params = {
    id: req.params.id,
    ...req.body,
  };
  tenderQuotationService
    .update(params)
    .then((result) => res.json(result))
    .catch(next);
}

function submit(req, res, next) {
  tenderQuotationService
    .submit(req.body)
    .then((result) => res.json(result))
    .catch(next);
}

function _delete(req, res, next) {
  tenderQuotationService
    .delete(req.params.id)
    .then((result) => res.json(result))
    .catch(next);
}

function uploadFiles(req, res, next) {
  if (!req.files || req.files.length === 0) {
    return res.status(400).json({
      success: false,
      message: "No files uploaded!"
    });
  }

  const filesData = req.files.map((file) => ({
    filename: file.filename,
    size: file.size,
    type: file.mimetype,
  }));

  const params = {
    tenderquotation_id: req.params.tenderquotationId,
    filesData: filesData,
    modified_by: req.user?.id || 1,
    owner: req.user?.id || 1,
  };

  tenderQuotationService
    .uploadFiles(params)
    .then((result) => res.json(result))
    .catch(next);
}
