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

const workActivityFilesDir = path.resolve(__dirname, "../../../../public/data/work-activity-files");
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    if (!fs.existsSync(workActivityFilesDir)) {
      fs.mkdirSync(workActivityFilesDir, { recursive: true });
    }
    cb(null, workActivityFilesDir);
  },
  filename: function (req, file, cb) {
    const safeName = (file.originalname || "file").replace(/[^a-zA-Z0-9._-]/g, "_");
    cb(null, Date.now() + "-" + safeName);
  },
});
const upload = multer({
  storage,
  limits: { fileSize: 15 * 1024 * 1024 },
  fileFilter: function (req, file, cb) {
    const allowed = [
      "application/pdf",
      "application/msword",
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      "image/jpeg",
      "image/png",
      "image/webp",
    ];
    if (allowed.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error("Only PDF, DOC, DOCX, or images (JPEG/PNG/WebP) are allowed."));
    }
  },
});

router.post("/create", authorize(), create);
router.post("/create-workflow", authorize(), createWorkflow);
router.post("/upload-files", authorize(), upload.array("files", 10), uploadFiles);
router.post("/", authorize(), getAll);
router.post("/option", authorize(), option);
router.post("/option-free", 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;

/**
 * Create a new gender
 * @param {Object} req.body - The gender data
 * @param {Object} res - The response object
 * @param {Function} next - The next middleware function
 * @returns {Promise} - A promise resolving to the created gender
 */
function create(req, res, next) {
  workActivityService
    .create(req.body)
    .then((result) => res.json(result))
    .catch(next);
}

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

/**
 * Get a list of all genders
 * @param {Object} req.query - The query object
 * @param {Object} res - The response object
 * @param {Function} next - The next middleware function
 * @returns {Promise} - A promise resolving to an array of genders
 */
function getAll(req, res, next) {
  workActivityService
    .getAll(req.body)
    .then((result) => res.json(result))
    .catch(next);
}

/**
 * Get an array of gender objects to be used as options in a select box
 * @param {Object} req.query - The query object
 * @param {Object} res - The response object
 * @param {Function} next - The next middleware function
 * @returns {Promise} - A promise resolving to an array of gender objects
 */
function option(req, res, next) {
  workActivityService
    .option(req.body)
    .then((result) => res.json(result))
    .catch(next);
}

/**
 * Count the number of genders matching a query
 * @param {Object} req.query - The query object
 * @param {Object} res - The response object
 * @param {Function} next - The next middleware function
 * @returns {Promise} - A promise resolving to the count of genders
 */
function count(req, res, next) {
  workActivityService
    .count(req.query)
    .then((result) => res.json(result))
    .catch(next);
}

/**
 * Update an existing gender
 * @param {number} req.params.id - The gender ID to be updated
 * @param {Object} req.body - The gender data to be updated
 * @param {Object} res - The response object
 * @param {Function} next - The next middleware function
 * @returns {Promise} - A promise resolving to the updated gender
 */
function update(req, res, next) {
  workActivityService
    .update(req.params.id, req.body)
    .then((result) => res.json(result))
    .catch(next);
}

/**
 * Enable or disable a gender
 * @param {number} req.params.id - The gender ID to be enabled/disabled
 * @param {Object} req.body - The gender data to be updated
 * @param {boolean} req.body.enabled - The enabled status of the gender
 * @param {Object} res - The response object
 * @param {Function} next - The next middleware function
 * @returns {Promise} - A promise resolving to the result of the enable/disable process
 */
function enabled(req, res, next) {
  workActivityService
    .enabled(req.params.id, req.body)
    .then((result) => res.json(result))
    .catch(next);
}

/**
 * Delete a gender
 * @param {number} req.params.id - The gender ID to be deleted
 * @param {Object} res - The response object
 * @param {Function} next - The next middleware function
 * @returns {Promise} - A promise resolving to the result of the deletion process
 */
function _delete(req, res, next) {
  workActivityService
    .delete(req.params.id)
    .then((result) => res.json(result))
    .catch(next);
}

function uploadFiles(req, res, next) {
  if (!req.files || req.files.length === 0) {
    return res.status(400).json({
      success: false,
      message: "No files uploaded!",
    });
  }
  const files = req.files.map((file) => ({
    file_name: file.originalname,
    file_path: `data/work-activity-files/${file.filename}`,
  }));
  return res.json({
    success: true,
    message: "Files uploaded successfully.",
    files,
  });
}
