const express = require("express");
const router = express.Router();
const authorize = require("../../../../middlewares/authorize-sapps");
const internalAuditService = require("./internalAudit.service");

const multer = require("multer");

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./public/data/documents/");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + "-" + file.originalname);
  },
});

const upload = multer({ storage: storage });

router.post("/create", authorize(), create);
router.post("/create-finding-item", authorize(), upload.single("files"), createOrUpdateFindingItemAudit);
router.get("/", authorize(), getAll);
router.get("/finding-by-item-id/:id", authorize(), getFindingByItemId);
router.get("/filter", authorize(), filter);
router.get("/option", authorize(), option);
router.get("/count", authorize(), count);
router.put("/:id", authorize(), update);
router.put("/enabled/:id", authorize(), enabled);
router.delete("/:id", authorize(), _delete);

module.exports = router;

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

function createOrUpdateFindingItemAudit(req, res, next) {
  // req.file berisi info file yang diupload
  // req.body berisi data form lainnya

  // Gabungkan data form dan file path ke params
  const params = {
    ...req.body,
    files: req.file ? req.file.filename : null,
  };

  internalAuditService
    .createOrUpdateFindingItemAudit(params)
    .then((result) => res.json(result))
    .catch(next);
}

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

function filter(req, res, next) {
  internalAuditService
    .filter(req.query)
    .then((result) => res.json(result))
    .catch(next);
}

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

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

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

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

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

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