const express = require("express");
const router = express.Router();
const authorize = require("../../../../middlewares/authorize-sapps");
const tenderService = require("./tender.service");
const redisClient = require('../../../../redisClient');

const fs = require('fs');
const path = require('path');
const multer = require('multer');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
      const dest = path.resolve(__dirname, "../../../../public/data/documents/tenders");
  
      // ✅ 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) {
    // hanya izinkan PDF
    if (file.mimetype !== "application/pdf") {
      return cb(new Error("Hanya file PDF yang diperbolehkan!"));
    }
    cb(null, true);
  },
});

router.post("/create", authorize(), upload.array("files", 10), create);
router.post("/", authorize(), getAll);
router.post("/show", show);
router.post("/option", authorize(), option);
router.post("/award", authorize(), award);
router.get("/count", authorize(), count);
router.put("/:id", authorize(), upload.array("files", 10), update);
router.put('/enabled/:id', authorize(), enabled);
router.delete("/:id", authorize(), _delete);

module.exports = router;

function create(req, res, next) {
  const filesData = req.files.map((file) => ({
    filename: file.filename, // Use originalname to store the original file name
    storedFilename: file.filename, // Store the generated filename for retrieval
    type: file.mimetype,
    size: file.size,
  }));

  const params = {
    ...req.body,
    filesData
  };

  tenderService
    .create(params)
    .then((result) => res.json(result))
    .catch(next);
}

function update(req, res, next) {
   let filesData = [];
    if (req.files && req.files.length > 0) {
        filesData = req.files.map((file) => ({
            filename: file.filename,
            type: file.mimetype,
            size: file.size,
        }));
    }

    // ✅ Ambil existingFiles dari body (jika ada)
    let existingFiles = [];
    if (req.body.existingFiles) {
        try {
            existingFiles = JSON.parse(req.body.existingFiles);
        } catch (err) {
            return res.status(400).json({ success: false, message: 'Invalid JSON format in existingFiles' });
        }
    }

    const params = {
        id: req.params.id,
        ...req.body,
        filesData,
        existingFiles // ⬅️ kirim ke service
    };
    // Memanggil service layer untuk memperbarui MOM
    tenderService
        .update(params) // Mengirimkan seluruh objek params
        .then((result) => res.json(result))
        .catch(next);
}

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

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

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


async function option(req, res, next) {
    try {
        // Membuat cacheKey
        const cacheKey = `provinces-options`;

        // Mengecek apakah data sudah ada di Redis
        const cachedData = await redisClient.get(cacheKey);
        if (cachedData) {
            return res.json(JSON.parse(cachedData));
        }

        // Jika tidak ada, panggil tenderService.option()
        const result = await tenderService.option();

        // Simpan hasilnya ke Redis dengan expire time misalnya 60 detik
        await redisClient.setEx(cacheKey, 60, JSON.stringify(result));

        // Kembalikan response JSON dari hasil panggilan service
        return res.json(result);
    } catch (error) {
        return next(error);
    }
}

// function option(req, res, next) {
//     tenderService
//         .option()
//         .then((result) => res.json(result))
//         .catch(next);
// }

function count(req, res, next) {
    tenderService
        .count()
        .then((result) => res.json(result))
        .catch(next);
}

function enabled(req, res, next) {
    tenderService.enabled(req.params.id, req.body)
        .then(result => res.json(result))
        .catch(next);
}

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