const express = require("express");
const router = express.Router();
const multer = require("multer");
const authorize = require("../../../../middlewares/authorize-sapps");
const callPlanServices = require("./callPlan.service");
const redisClient = require("../../../../redisClient");
const sharp = require("sharp");
const fs = require("fs");
const path = require("path");

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const dest = path.resolve(__dirname, "../../../../public/data/images/visitverify/tmp");

    // ✅ Auto create folder if not exists
    if (!fs.existsSync(dest)) {
      fs.mkdirSync(dest, { recursive: true });
    }

    cb(null, dest);
  },
  filename: function (req, file, cb) {
    const ext = path.extname(file.originalname);
    const tempName = `TEMP-${Date.now()}${ext}`;
    cb(null, tempName);
  },
});

const upload = multer({
  storage,
  fileFilter: function (req, file, cb) {
    if (!file.mimetype.startsWith("image/")) {
      cb(new Error("Hanya file gambar yang diperbolehkan!"), false);
    } else {
      cb(null, true);
    }
  },
});

router.post("/create", authorize(), create);
router.post("/create-workflow", authorize(), createWorkflow);
// router.post("/create-realization", authorize(), createRealization);
router.post("/create-realization", authorize(), upload.single("filename"), createRealization);
router.post("/generate-doc-no", authorize(), generateDocumentNo);
router.post("/bulk-visit", authorize(), bulkCreateVisit);
router.get("/filter", authorize(), filter);
router.get("/", authorize(), getAll);
router.get("/plan-by-territory-for-uc", authorize(), getPlanByTerritoryForUC);
router.get("/:id", authorize(), getCallPlanById);
router.get("/option", authorize(), option);
router.get("/count", authorize(), count);
router.get("/destination-by-plan-id/:id", authorize(), getDestinationByCallPlanId);
router.get("/realization/:id", authorize(), realizationByPlanId);
router.put("/:id", authorize(), update);
// router.put("/realization/:id", authorize(), updateRealization);
router.put("/realization/:id", authorize(), upload.single("filename"), updateRealization);
router.put("/update-workflow/:id", authorize(), updateWorkflow);
router.put("/enabled/:id", authorize(), enabled);
router.delete("/:id", authorize(), _delete);
router.delete("/realization/:id", authorize(), deleteCallRealizaion);
router.delete("/reset-visit-plan/:id", authorize(), resetVisitPlan);

module.exports = router;

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

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

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

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

function getCallPlanById(req, res, next) {
  callPlanServices
    .getCallPlanById(req.params.id)
    .then((result) => res.json(result))
    .catch(next);
}

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

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

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

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

function realizationByPlanId(req, res, next) {
  callPlanServices
    .realizationByPlanId(req.params.id)
    .then((result) => res.json(result))
    .catch(next);
}

function getDestinationByCallPlanId(req, res, next) {
  callPlanServices
    .getDestinationByCallPlanId(req.params.id)
    .then((result) => res.json(result))
    .catch(next);
}

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

async function createRealization(req, res, next) {
  try {
    let compressedFilename = null;

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

      // amankan semua karakter aneh di nama file
      const safe = (text) => (text ? text.replace(/[^a-z0-9]/gi, "_").toUpperCase() : "UNKNOWN");

      const compressedName = `CPR-${req.file.filename.split(".")[0]}.webp`;
      const finalDir = path.resolve(__dirname, "../../../../public/data/images/visitverify");

      const outputPath = path.join(finalDir, compressedName);

      // ✅ pastikan folder final ada
      if (!fs.existsSync(finalDir)) {
        fs.mkdirSync(finalDir, { recursive: true });
      }
      await sharp(inputPath).resize({ width: 1000 }).webp({ quality: 70 }).toFile(outputPath);

      // hapus file temp pakai delay
      setTimeout(() => {
        if (fs.existsSync(inputPath)) {
          fs.unlink(inputPath, (err) => {
            if (err) console.log("Gagal hapus temp:", err.message);
          });
        }
      }, 500);

      compressedFilename = compressedName;
    }

    const createData = {
      ...req.body,
      filename: compressedFilename,
    };

    const result = await callPlanServices.createRealization(createData);
    res.json(result);
  } catch (error) {
    console.error(error);
    next(error);
  }
}

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

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

      const safe = (text) => (text ? text.replace(/[^a-z0-9]/gi, "_").toUpperCase() : "UNKNOWN");
      const compressedName = `CPR-${req.file.filename.split(".")[0]}.webp`;
      const outputPath = path.join(__dirname, "../../../../public/data/images/visitverify", compressedName);

      await sharp(inputPath).resize({ width: 1000 }).webp({ quality: 70 }).toFile(outputPath);

      // hapus temp file update
      setTimeout(() => {
        fs.unlink(inputPath, (err) => {
          if (err) console.error("❌ Update temp gagal dihapus:", err.message);
          else console.log("✅ Update temp dihapus");
        });
      }, 500);

      compressedFilename = compressedName;
    }

    const updateData = {
      ...req.body,
      filename: compressedFilename,
    };

    const result = await callPlanServices.updateRealization(req.params.id, updateData);

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

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

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

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

function deleteCallRealizaion(req, res, next) {
  callPlanServices
    .deleteCallRealizaion(req.params.id)
    .then((result) => res.json(result))
    .catch(next);
}

function resetVisitPlan(req, res, next) {
  callPlanServices
    .resetVisitPlan(req.params.id)
    .then((result) => res.json(result))
    .catch(next);
}
