const express = require("express");
const router = express.Router();
const multer = require("multer");
const authorize = require("../../../../middlewares/authorize-sapps");
const ncProductService = require("./ncProduct.service");

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(),
  upload.fields([
    { name: "bast_file", maxCount: 1 },
    { name: "creditnote_file", maxCount: 1 },
    { name: "productcondition_file", maxCount: 1 },
  ]),
  create
);
router.get("/", authorize(), getAll);
router.get("/filter", authorize(), filter);
router.get("/option", authorize(), option);
router.get("/option-parent", authorize(), optionParent);
router.get("/filter-by-year", authorize(), filterByYear);
router.get("/count", authorize(), count);
router.put(
  "/:id",
  authorize(),
  upload.fields([
    { name: "bast_file", maxCount: 1 },
    { name: "creditnote_file", maxCount: 1 },
    { name: "productcondition_file", maxCount: 1 },
  ]),
  update
);
router.put("/enabled/:id", authorize(), enabled);
router.delete("/:id", authorize(), _delete);

module.exports = router;

function create(req, res, next) {
  const data = {
    ...req.body,
    bast_file: req.files["bast_file"]
      ? req.files["bast_file"][0].filename
      : null,
      creditnote_file: req.files["creditnote_file"]
      ? req.files["creditnote_file"][0].filename
      : null,
      productcondition_file: req.files["productcondition_file"]
      ? req.files["productcondition_file"][0].filename
      : null,
  };

  ncProductService
    .create(data)
    .then((result) => res.json(result))
    .catch(next);
}

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

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

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

function optionParent(req, res, next) {
  ncProductService
    .optionParent()
    .then((result) => res.json(result))
    .catch(next);
}
function filterByYear(req, res, next) {
  ncProductService
    .filterByYear(req.query)
    .then((result) => res.json(result))
    .catch(next);
}

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

function update(req, res, next) {
  // Handle bast file existing yang dikirim sebagai object dari frontend
  const existingBASTFile = req.body.bast_file;
  let BASTFilename = '';

  // Cek jika bast file adalah object (kasus edit tanpa perubahan file)
  if (typeof existingBASTFile === 'object' && existingBASTFile !== null) {
    BASTFilename = existingBASTFile.filename || existingBASTFile.name || '';
  } else {
    BASTFilename = existingBASTFile;
  }

  // Handle creditnote file existing yang dikirim sebagai object dari frontend
  const existingCreditNoteFile = req.body.creditnote_file;
  let creditNoteFilename = '';

  // Cek jika adalah object (kasus edit tanpa perubahan file)
  if (typeof existingCreditNoteFile === 'object' && existingCreditNoteFile !== null) {
    creditNoteFilename = existingCreditNoteFile.filename || existingCreditNoteFile.name || '';
  } else {
    creditNoteFilename = existingCreditNoteFile;
  }

  // Handle creditnote file existing yang dikirim sebagai object dari frontend
  const existingProductConditionFile = req.body.productcondition_file;
  let productConditionFilename = '';

  // Cek jika adalah object (kasus edit tanpa perubahan file)
  if (typeof existingProductConditionFile === 'object' && existingProductConditionFile !== null) {
    productConditionFilename = existingProductConditionFile.filename || existingProductConditionFile.name || '';
  } else {
    productConditionFilename = existingProductConditionFile;
  }

  const updateData = {
    ...req.body,
    bast_file: req.files["bast_file"] 
      ? req.files["bast_file"][0].filename // File baru
      : BASTFilename, // Gunakan filename dari object/string
    
      creditnote_file: req.files["creditnote_file"]
      ? req.files["creditnote_file"][0].filename
      : creditNoteFilename,

      productcondition_file: req.files["productcondition_file"]
      ? req.files["productcondition_file"][0].filename
      : productConditionFilename
  };

  ncProductService
    .update(req.params.id, updateData)
    .then((result) => res.json(result))
    .catch(next);
}

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

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