const express = require("express");
const router = express.Router();
const authorize = require("../../../../middlewares/authorize-sapps");
const dmsRegulatoryService = require("./dmsRegulatory.service");
const redisClient = require("../../../../redisClient");
const multer = require("multer");
const storageEngine = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./public/data/documents");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + "-" + file.originalname);
  },
});

// set up multer for handling file uploads
const upload = multer({ storage: storageEngine });

// router.post(
//   "/create",
//   upload.fields([
//     { name: "document_1", maxCount: 1 },
//     { name: "document_2", maxCount: 1 },
//     { name: "document_3", maxCount: 1 },
//     { name: "history_doc", maxCount: 1 },
//     { name: "history_doc2", maxCount: 1 },
//     { name: "history_doc3", maxCount: 1 },
//     { name: "history_doc4", maxCount: 1 },
//     { name: "history_doc5", maxCount: 1 },
//   ]),
//   (req, res, next) => {
//     const body = req.body;
//     const files = req.files;
//     const baseUrlDocument = "https://sapharmaco-backend.sapharma.co.id/documents/";

//     Object.keys(files).forEach((key) => {
//       if (files[key]) {
//         body[key] = baseUrlDocument + files[key][0].filename;
//       }
//     });

//     dmsRegulatoryService
//       .create(body)
//       .then((result) => res.json(result))
//       .catch(next);
//   }
// );

router.post(
  "/create",
  upload.fields([
    { name: "document_1", maxCount: 1 },
    { name: "document_2", maxCount: 1 },
    { name: "document_3", maxCount: 1 },
    { name: "history_doc", maxCount: 1 },
    { name: "history_doc2", maxCount: 1 },
    { name: "history_doc3", maxCount: 1 },
    { name: "history_doc4", maxCount: 1 },
    { name: "history_doc5", maxCount: 1 },
  ]),
  (req, res, next) => {
    const baseUrlDocument = "https://sapharmaco-backend.sapharma.co.id/documents/";

    // Mendapatkan informasi file yang diunggah
    const files = req.files;

    // Membuat objek body yang akan digunakan untuk menyimpan data
    let body = {
      creation: req.body.creation,
      modified: req.body.modified,
      modified_by: req.body.modified_by,
      owner: req.body.owner,
      enabled: req.body.enabled,
      display_name: req.body.display_name,
      date: req.body.date,
      expired_date: req.body.expired_date,
      reminder_day: req.body.reminder_day,
      notification_date: req.body.notification_date,
      issue_date: req.body.issue_date,
      document_number: req.body.document_number,
      documentgroup_id: req.body.documentgroup_id,
      team: req.body.team,
      team_permission: req.body.team_permission,
      user_info: req.body.user_info,
      is_private: req.body.is_private,
      nie: req.body.nie,
      history_desc: req.body.history_desc,
      history_desc2: req.body.history_desc2,
      history_desc3: req.body.history_desc3,
      history_desc4: req.body.history_desc4,
      history_desc5: req.body.history_desc5,
      history_date: req.body.history_date,
      history_date2: req.body.history_date2,
      history_date3: req.body.history_date3,
      history_date4: req.body.history_date4,
      history_date5: req.body.history_date5,
      company_id: req.body.company_id,
    };
    console.log("isi body", body);
    // Menambahkan URL file ke body jika file diunggah
    if (files["document_1"]) {
      body.document_1 = baseUrlDocument + files["document_1"][0].filename;
    }
    if (files["document_2"]) {
      body.document_2 = baseUrlDocument + files["document_2"][0].filename;
    }
    if (files["document_3"]) {
      body.document_3 = baseUrlDocument + files["document_3"][0].filename;
    }
    if (files["history_doc"]) {
      body.history_doc = baseUrlDocument + files["history_doc"][0].filename;
    }
    if (files["history_doc2"]) {
      body.history_doc2 = baseUrlDocument + files["history_doc2"][0].filename;
    }
    if (files["history_doc3"]) {
      body.history_doc3 = baseUrlDocument + files["history_doc3"][0].filename;
    }
    if (files["history_doc4"]) {
      body.history_doc4 = baseUrlDocument + files["history_doc4"][0].filename;
    }
    if (files["history_doc5"]) {
      body.history_doc5 = baseUrlDocument + files["history_doc5"][0].filename;
    }

    dmsRegulatoryService
      .create(body)
      .then((result) => res.json(result))
      .catch(next);
  }
);

router.post("/", authorize(), getAll);
router.post("/option", authorize(), option);
router.get("/count", authorize(), count);
router.put(
  "/:id",
  authorize(),
  upload.fields([
    { name: "document_1", maxCount: 1 },
    { name: "document_2", maxCount: 1 },
    { name: "document_3", maxCount: 1 },
    { name: "history_doc", maxCount: 1 },
    { name: "history_doc2", maxCount: 1 },
    { name: "history_doc3", maxCount: 1 },
    { name: "history_doc4", maxCount: 1 },
    { name: "history_doc5", maxCount: 1 },
  ]),
  (req, res, next) => {
    // Mendapatkan informasi file yang diunggah
    const files = req.files;
    const baseUrlDocument = "https://sapharmaco-backend.sapharma.co.id/documents/";

    // Membuat objek body yang akan digunakan untuk menyimpan data
    let body = {
      creation: req.body.creation,
      modified: req.body.modified,
      modified_by: req.body.modified_by,
      owner: req.body.owner,
      enabled: req.body.enabled,
      display_name: req.body.display_name,
      date: req.body.date,
      issue_date: req.body.issue_date,
      document_number: req.body.document_number,
      expired_date: req.body.expired_date,
      reminder_day: req.body.reminder_day,
      notification_date: req.body.notification_date,
      documentgroup_id: req.body.documentgroup_id,
      team: req.body.team,
      team_permission: req.body.team_permission,
      user_info: req.body.user_info,
      is_private: req.body.is_private,
      nie: req.body.nie,
      history_desc: req.body.history_desc,
      history_desc2: req.body.history_desc2,
      history_desc3: req.body.history_desc3,
      history_desc4: req.body.history_desc4,
      history_desc5: req.body.history_desc5,
      history_date: req.body.history_date,
      history_date2: req.body.history_date2,
      history_date3: req.body.history_date3,
      history_date4: req.body.history_date4,
      history_date5: req.body.history_date5,
      company_id: req.body.company_id,
    };

    // Menambahkan URL file ke body jika file diunggah
    if (files["document_1"]) {
      body.document_1 = baseUrlDocument + files["document_1"][0].filename;
    }
    if (files["document_2"]) {
      body.document_2 = baseUrlDocument + files["document_2"][0].filename;
    }
    if (files["document_3"]) {
      body.document_3 = baseUrlDocument + files["document_3"][0].filename;
    }
    if (files["history_doc"]) {
      body.history_doc = baseUrlDocument + files["history_doc"][0].filename;
    }
    if (files["history_doc2"]) {
      body.history_doc2 = baseUrlDocument + files["history_doc2"][0].filename;
    }
    if (files["history_doc3"]) {
      body.history_doc3 = baseUrlDocument + files["history_doc3"][0].filename;
    }
    if (files["history_doc4"]) {
      body.history_doc4 = baseUrlDocument + files["history_doc4"][0].filename;
    }
    if (files["history_doc5"]) {
      body.history_doc5 = baseUrlDocument + files["history_doc5"][0].filename;
    }

    // Memastikan request tidak mengirim data file yang sudah ada (jika tidak diganti)
    if (!files["document_1"] && req.body.document_1) {
      body.document_1 = req.body.document_1;
    }
    if (!files["document_2"] && req.body.document_2) {
      body.document_2 = req.body.document_2;
    }
    if (!files["document_3"] && req.body.document_3) {
      body.document_3 = req.body.document_3;
    }
    if (!files["history_doc"] && req.body.history_doc) {
      body.history_doc = req.body.history_doc;
    }
    if (!files["history_doc2"] && req.body.history_doc2) {
      body.history_doc2 = req.body.history_doc2;
    }
    if (!files["history_doc3"] && req.body.history_doc3) {
      body.history_doc3 = req.body.history_doc3;
    }
    if (!files["history_doc4"] && req.body.history_doc4) {
      body.history_doc4 = req.body.history_doc4;
    }
    if (!files["history_doc5"] && req.body.history_doc5) {
      body.history_doc5 = req.body.history_doc5;
    }

    // Memanggil service untuk melakukan operasi update
    dmsRegulatoryService
      .update(req.params.id, body)
      .then((result) => res.json(result))
      .catch(next);
  }
);

router.put("/enabled/:id", authorize(), enabled);
router.delete("/:id", authorize(), _delete);

module.exports = router;

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

async function option(req, res, next) {
  try {
    // Membuat cacheKey
    const cacheKey = `dmsregulatory-options`;

    // Mengecek apakah data sudah ada di Redis
    const cachedData = await redisClient.get(cacheKey);
    if (cachedData) {
      return res.json(JSON.parse(cachedData));
    }

    // Jika tidak ada, panggil dmsRegulatoryService.option()
    const result = await dmsRegulatoryService.option();

    // Simpan hasilnya ke Redis dengan expire time misalnya 60 detik
    await redisClient.setEx(cacheKey, 60, JSON.stringify(result));

    // Kembalikan response JSON dari hasil panggilan service
    return res.json(result);
  } catch (error) {
    return next(error);
  }
}

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

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

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

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

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