const express = require("express");
const router = express.Router();
const authorize = require("../../../../middlewares/authorize-sapps");
const procurementTrackerService = require("./procurementTracker.service");
const redisClient = require("../../../../redisClient");
const multer = require("multer");
const fs = require("fs");
const path = require("path");


const storage = multer.diskStorage({
  destination: function (req, file, cb) {
      const dest = path.resolve(__dirname, "../../../../public/data/documents/procurementtrackers");
  
      // ✅ 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: 2 * 1024 * 1024, // maksimal 2MB
  },
  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-file", authorize(), upload.single("file"), createFile);
router.post("/create", authorize(), create);
router.post("/", authorize(), getAll);
router.post("/get-files", authorize(), getFiles);
router.post("/option", authorize(), option);
router.get("/count", authorize(), count);
router.get("/last-doc-no", authorize(), getLastDocNo);
router.put("/:id", authorize(), update);
router.put("/update-file/:id", authorize(), upload.single("file"), updateFile);
router.put("/enabled/:id", authorize(), enabled);
router.delete("/:id", authorize(), _delete);
router.delete("/delete-file/:id", authorize(), deleteFile);

module.exports = router;

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

function createFile(req, res, next) {
  if (!req.file) {
    return res.status(400).json({ error: "File belum diupload!" });
  }

  // Bisa simpan path-nya di DB via service
  const fileData = {
    ...req.body,
    file_path: req.file.path,
    file_name: req.file.filename,
    file_size: req.file.size,
    file_type: req.file.mimetype, //
  };

  procurementTrackerService
    .createFile(fileData)
    .then((result) => res.json(result))
    .catch(next);
}

async function updateFile(req, res, next) {
  try {
    const id = req.params.id;

    // Jika user tidak upload file baru
    if (!req.file) {
      return res.status(400).json({ success: false, message: "File belum diupload!" });
    }

    // Data file baru
    const fileData = {
      ...req.body,
      file_path: req.file.path,
      file_name: req.file.filename,
      file_size: req.file.size,
      file_type: req.file.mimetype,
    };

    const result = await procurementTrackerService.updateFile(id, fileData);
    return res.json(result);
  } catch (error) {
    next(error);
  }
}

async function getLastDocNo(req, res, next) {
  procurementTrackerService
    .getLastDocNo()
    .then((result) => res.json(result))
    .catch(next);
}

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

function getFiles(req, res, next) {
  procurementTrackerService
    .getFiles(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 procurementTrackerService.option()
    const result = await procurementTrackerService.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) {
//     procurementTrackerService
//         .option()
//         .then((result) => res.json(result))
//         .catch(next);
// }

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

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

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

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

function deleteFile(req, res, next) {
  procurementTrackerService
    .deleteFile(req.params.id)
    .then((result) => res.json(result))
    .catch(next);
}
