const express = require("express");
const router = express.Router();
const authorize = require("../../../../middlewares/authorize-sapps");
const provinceService = require("./province.service");
const redisClient = require("../../../../redisClient");
const crypto = require("crypto");

const stableStringify = (value) => {
	if (value === null || value === undefined) return String(value);
	if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
	if (typeof value !== "object") return JSON.stringify(value);

	const keys = Object.keys(value).sort();
	return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;
};

const hashObject = (obj) => {
	const raw = stableStringify(obj || {});
	return crypto.createHash("sha1").update(raw).digest("hex");
};

async function invalidateProvinceCaches() {
	try {
		await redisClient.delByPrefix("provinces:");
		await redisClient.del("provinces-options");

		// Provinces are joined into cities responses; keep cities caches consistent too
		await redisClient.delByPrefix("cities:");
		await redisClient.delByPrefix("cities-options:");
	} catch (e) {
		// best-effort cache invalidation
		console.error("Failed to invalidate province caches:", e?.message || e);
	}
}

router.post("/create", authorize(), create);
router.post("/", authorize(), getAll);
router.post("/option", authorize(), option);
router.get("/count", authorize(), count);
router.put("/:id", authorize(), update);
router.put("/enabled/:id", authorize(), enabled);
router.delete("/:id", authorize(), _delete);

module.exports = router;

async function create(req, res, next) {
	try {
		const result = await provinceService.create(req.body);
		if (result?.success) await invalidateProvinceCaches();
		return res.json(result);
	} catch (e) {
		return next(e);
	}
}

async function getAll(req, res, next) {
	try {
		// Cache key MUST vary by filters/sort/pagination params.
		// Use stable hash (order-independent) to avoid duplicate/missed caches.
		const cacheKey = `provinces:${hashObject(req.body)}`;

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

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

async function option(req, res, next) {
	try {
		// Membuat cacheKey
		const cacheKey = `provinces-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 provinceService.option()
		const result = await provinceService.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) {
//     provinceService
//         .option()
//         .then((result) => res.json(result))
//         .catch(next);
// }

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

async function update(req, res, next) {
	try {
		const result = await provinceService.update(req.params.id, req.body);
		if (result?.success) await invalidateProvinceCaches();
		return res.json(result);
	} catch (e) {
		return next(e);
	}
}

async function enabled(req, res, next) {
	try {
		const result = await provinceService.enabled(req.params.id, req.body);
		if (result?.success) await invalidateProvinceCaches();
		return res.json(result);
	} catch (e) {
		return next(e);
	}
}

async function _delete(req, res, next) {
	try {
		const result = await provinceService.delete(req.params.id);
		if (result?.success) await invalidateProvinceCaches();
		return res.json(result);
	} catch (e) {
		return next(e);
	}
}
