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

async function invalidateCityCaches() {
	try {
		await redisClient.delByPrefix("cities:");
		await redisClient.delByPrefix("cities-options:");

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

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");
};

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 cityService.create(req.body);
		if (result?.success) await invalidateCityCaches();
		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 (otherwise filters appear broken)
		const cacheKey = `cities:${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 cityService.getAll()
		const result = await cityService.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) {
//   cityService
//     .getAll()
//     .then((result) => res.json(result))
//     .catch(next);
// }

async function option(req, res, next) {
	try {
		// Cache key MUST vary by request body (e.g., province_id), otherwise filtered options appear broken
		const cacheKey = `cities-options:${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 cityService.option(params)
		const result = await cityService.option(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 option(req, res, next) {
//   cityService
//     .option()
//     .then((result) => res.json(result))
//     .catch(next);
// }

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

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

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

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