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

const storage = multer.diskStorage({
   destination: function (req, file, cb) {
      const dest = path.resolve(__dirname, "../../../../public/data/documents/upcountries/tmp");
  
      // ✅ Auto create folder if not exists
      if (!fs.existsSync(dest)) {
        fs.mkdirSync(dest, { recursive: true });
      }
  
      cb(null, dest);
    },
  filename: function (req, file, cb) {
    cb(null, Date.now() + "-" + file.originalname);
  },
});

const upload = multer({
  storage,
  limits: {
    fileSize: 2 * 1024 * 1024, // 2MB
  },
  fileFilter: (req, file, cb) => {
    const allowedTypes = [
      "application/pdf",
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    ];

    if (!allowedTypes.includes(file.mimetype)) {
      return cb(
        new multer.MulterError(
          "LIMIT_UNEXPECTED_FILE",
          "Format file tidak diizinkan. Gunakan PDF atau DOCX"
        )
      );
    }

    cb(null, true);
  }
});

router.post("/", authorize(), getAll);
router.post("/create", authorize(), create);
router.post("/generate-doc-no", authorize(), generateDocumentNo);
router.post("/request-ga", authorize(), requestGA);
router.get("/filter", authorize(), filter);
router.get("/option", authorize(), option);
router.get("/count", authorize(), count);
router.put("/:id", authorize(), update);
router.put(
  "/update-file/:id",
  authorize(),
  (req, res, next) => {
    upload.single("files")(req, res, function (err) {
      if (err instanceof multer.MulterError) {
        // Error dari multer
        if (err.code === "LIMIT_FILE_SIZE") {
          return res.status(400).json({
            success: false,
            message: "Ukuran file terlalu besar. Maksimal 2MB"
          });
        }

        return res.status(400).json({
          success: false,
          message: err.message
        });
      } else if (err) {
        // Error lain
        return res.status(400).json({
          success: false,
          message: "Upload file gagal"
        });
      }

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

module.exports = router;

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

async function updateFile(req, res, next) {
  try {
    let filenameToSave = req.body.filename || null;

    if (req.file) {
      const inputPath = req.file.path;
      const originalFilename = req.file.filename;

      const finalDestinationDir = path.resolve(
        __dirname,
        "../../../../public/data/documents/upcountries"
      );

      if (!fs.existsSync(finalDestinationDir)) {
        fs.mkdirSync(finalDestinationDir, { recursive: true });
      }

      const outputPath = path.join(finalDestinationDir, originalFilename);
      await fs.promises.rename(inputPath, outputPath);

      filenameToSave = originalFilename;
    }

    const updateData = {
      ...req.body,
      files: filenameToSave,
    };

    const result = await upCountryService.updateFile(
      req.params.id,
      updateData
    );

    return res.json(result);
  } catch (error) {
    next(error);
  }
}


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

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

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

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

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

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

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

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

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