const express = require("express");
const router = express.Router();
const multer = require("multer");
const authorize = require("../../../../middlewares/authorize-sapps");
const applicantService = require("./applicant.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: "cv", maxCount: 1 },
    { name: "psikotest_file", maxCount: 1 },
  ]),
  create
);
router.get("/", authorize(), getAll);
router.get("/by-user-id", authorize(), getApplicantByUserID);
router.get("/by-owner", authorize(), getApplicantByOwner);
router.get("/filter", authorize(), filter);
router.get("/filter-by-employee-request", authorize(), filterByEmployeeRequest);
router.get("/filter-by-job-posting", authorize(), filterByJobPosting);
router.get("/option", authorize(), option);
router.get("/option-parent", authorize(), optionParent);
router.get("/count", authorize(), count);
router.put(
  "/:id",
  authorize(),
  upload.fields([
    { name: "cv", maxCount: 1 },
    { name: "psikotest_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,
    cv: req.files["cv"]
      ? req.files["cv"][0].filename
      : null,
    psikotest_file: req.files["psikotest_file"]
      ? req.files["psikotest_file"][0].filename
      : null
  };

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

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

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

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

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

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

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

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

  // Handle CV existing yang dikirim sebagai object dari frontend
  const existingPsikotestFile = req.body.psikotest_file;
  let psikotestFilename = '';

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

  const updateData = {
    ...req.body,
    cv: req.files["cv"] 
      ? req.files["cv"][0].filename // File baru
      : cvFilename, // Gunakan filename dari object/string
    
      psikotest_file: req.files["psikotest_file"]
      ? req.files["psikotest_file"][0].filename
      : psikotestFilename
  };

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

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

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