const express = require("express");
const router = express.Router();
const multer = require("multer");
const Joi = require("joi");
const validateRequest = require("../../../../middlewares/validate-request");
const authorize = require("../../../../middlewares/authorize-sapps");
const idempotency = require("../../../../middlewares/idempotency");
const userService = require("./user.service");
const redisClient = require("../../../../redisClient");

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

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

router.post("/authenticate", authenticate);
router.post("/register", register);
router.post("/create", authorize(), upload.single("user_image"), create);
router.post("/", authorize(), getAll);
router.post("/option", authorize(), option);
router.post("/refresh", refresh);
router.get("/count", authorize(), count);
// New, safer endpoint: do not expose token in URL
router.get("/me", authorize(), me);
// Backward compatibility (old pattern where token was in URL)
router.get("/:servicetoken", authorize(), me);
router.put("/:id", authorize(), idempotency(), upload.single("user_image"), update);
router.put("/last/:id", authorize(), idempotency(), last);
router.put("/last-logout/:id", authorize(), idempotency(), lastLogout);
router.put("/enabled/:id", authorize(), idempotency(), enabled);
router.delete("/:id", authorize(), idempotency(), _delete);

module.exports = router;

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

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

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

	userService
		.create(userData)
		.then((result) => res.json(result))
		.catch(next);
}

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

function me(req, res, next) {
	// Prefer Authorization header; fall back to URL param for backward compatibility
	const authHeader = req.headers && req.headers.authorization;
	const tokenFromHeader = authHeader && authHeader.split(" ")[0] === "Bearer" ? authHeader.split(" ")[1] : null;
	const token = tokenFromHeader || req.params.servicetoken || req.query.token;

	userService
		.me(token)
		.then((result) => res.json(result))
		.catch(next);
}

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

function refresh(req, res, next) {
	// Expect { refreshToken } in body
	userService
		.refresh(req.body?.refreshToken)
		.then((result) => res.json(result))
		.catch(next);
}

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

function update(req, res, next) {
	const updateData = {
		...req.body,
		user_image: req.file ? req.file.filename : req.body.user_image ? req.body.user_image : null,
	};

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

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

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

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

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