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


const fs = require('fs');
const path = require('path');
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, file.originalname);
    }
});

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

router.post("/create", authorize(), upload.array("files", 10), create);
router.get("/", authorize(), getAll);
router.get("/filter", authorize(), filter);
router.get("/owner-or-participant", authorize(), filterOwnerOrParticipant);
router.get("/option", authorize(), option);
router.get("/count", authorize(), count);
router.put("/:id", authorize(), upload.array("files", 10), update);
router.put("/enabled/:id", authorize(), enabled);
router.delete("/:id", authorize(), _delete);

module.exports = router;

function create(req, res, next) {
   const filesData = req.files.map((file) => ({
    filename: file.originalname,
    path: file.path,
    size: file.size,
  }));

  const params = {
    ...req.body,
    filesData
    // files: req.file ? req.file.filename : null
  };
  
  momService
    .create(params)
    .then((result) => res.json(result))
    .catch(next);
}

/**
 * Controller untuk memperbarui data MOM.
 * Menerima ID MOM dari params, data dari request body, dan file yang diunggah ulang.
 */
function update(req, res, next) {
   let filesData = [];
    if (req.files && req.files.length > 0) {
        filesData = req.files.map((file) => ({
            filename: file.originalname,
            path: file.path.replace(/\\/g, '/'), // biar aman di frontend
            size: file.size,
        }));
    }

    // ✅ Ambil existingFiles dari body (jika ada)
    let existingFiles = [];
    if (req.body.existingFiles) {
        try {
            existingFiles = JSON.parse(req.body.existingFiles);
        } catch (err) {
            return res.status(400).json({ success: false, message: 'Invalid JSON format in existingFiles' });
        }
    }

    const params = {
        id: req.params.id,
        ...req.body,
        filesData,
        existingFiles // ⬅️ kirim ke service
    };
    // Memanggil service layer untuk memperbarui MOM
    momService
        .update(params) // Mengirimkan seluruh objek params
        .then((result) => res.json(result))
        .catch(next);
}

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

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

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

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

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




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

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