const express = require("express");
const router = express.Router();
const multer = require("multer");
const authorize = require("../../../../middlewares/authorize-sapps");
const permitEaseService = require("./permitEase.service");
const redisClient = require("../../../../redisClient");

const storage = multer.diskStorage({
	destination: function (req, file, cb) {
		cb(null, "./public/data/documents/");
	},
	filename: function (req, file, cb) {
		cb(null, Date.now() + "-" + file.originalname);
	},
});

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

router.post("/create", authorize(), upload.single("filename"), create);
router.post("/create-workflow", authorize(), createWorkflow);
router.get("/", authorize(), getAll);
router.get("/get-by-approver", authorize(), getByApprover);
router.get("/filter", authorize(), filter);
router.get("/option", authorize(), option);
router.get("/count", authorize(), count);
router.get("/get-filename/:id", getFilename);
router.put("/:id", authorize(), upload.single("filename"), update);
router.delete("/:id", authorize(), _delete);

module.exports = router;

function create(req, res, next) {
	const createData = {
		...req.body,
		filename: req.file ? req.file.filename : null,
	};

	permitEaseService
		.create(createData)
		.then((result) => res.json(result))
		.catch(next);
}

// async function getAll(req, res, next) {
//     try {
//         // Membuat cacheKey berdasarkan req.query
//         const cacheKey = `statuses:${JSON.stringify(req.query)}-permitEases`;

//         // 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 permitEaseService.getAll(req.query)
//         const result = await permitEaseService.getAll(req.query);

//         // 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 getAll(req, res, next) {
	permitEaseService
		.getAll(req.query)
		.then((result) => res.json(result))
		.catch(next);
}

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

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

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

function count(req, res, next) {
	permitEaseService
		.count()
		.then((result) => res.json(result))
		.catch(next);
}
function update(req, res, next) {
	const updateData = {
		...req.body,
		filename: req.file
			? req.file.filename
			: req.body.filename
			? req.body.filename
			: null,
	};

	permitEaseService
		.update(req.params.id, updateData)
		.then((result) => res.json(result))
		.catch(next);
}

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

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

function getFilename(req, res, next) {
	try {
		const filePath = path.join(
			__dirname,
			`../../../../public/data/documents/${req.params.id}`
		);

		if (!fs.existsSync(filePath)) {
			return res.status(404).json({ message: "File not found" });
		}

		res.setHeader("Content-Disposition", `inline; filename="${req.params.id}"`);
		res.setHeader("Content-Type", "application/pdf");

		res.sendFile(filePath, (err) => {
			if (err) {
				console.error("Error sending file: ", err);
				return res.status(500).json({ message: "Internal server error" });
			}
		});
	} catch (error) {
		console.error("Error in getFilename:", error);
		res.status(500).json({ message: "Internal server error" });
	}
}
