const express = require("express");
const router = express.Router();
const multer = require("multer");
const authorize = require("../../../../middlewares/authorize-sapps");
const productReturnService = require("./productReturn.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: "dr_file", maxCount: 1 },
    { name: "return_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("/count", authorize(), count);
router.put(
  "/:id",
  authorize(),
  upload.fields([
    { name: "dr_file", maxCount: 1 },
    { name: "return_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,
    return_file: req.files["return_file"]
      ? req.files["return_file"][0].filename
      : null,
      dr_file: req.files["dr_file"]
      ? req.files["dr_file"][0].filename
      : null
  };

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

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

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

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

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


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

function update(req, res, next) {
  // Handle CV existing yang dikirim sebagai object dari frontend
  const existingReturnFile = req.body.return_file;
  let ReturnFilename = '';

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

  // Handle CV existing yang dikirim sebagai object dari frontend
  const existingDRFile = req.body.dr_file;
  let drFilename = '';

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

  const updateData = {
    ...req.body,
    return_file: req.files["return_file"] 
      ? req.files["return_file"][0].filename // File baru
      : ReturnFilename, // Gunakan filename dari object/string
    
      dr_file: req.files["dr_file"]
      ? req.files["dr_file"][0].filename
      : drFilename,
  };

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

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

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