import { Router, Request, Response } from "express";
import client from "modules/discord";

const GUILD_ID = process.env.DISCORD_GUILD_ID;
if (!GUILD_ID) {
	throw new Error("DISCORD_GUILD_ID environment variable is not set.");
}

const router: Router = Router();

const getMember = async (memberId: string) => {
	const guild = client.guilds.cache.get(GUILD_ID);
	if (!guild) throw new Error("Guild not found");
	try {
		return guild.members.cache.get(memberId) ?? (await guild.members.fetch(memberId));
	} catch (error) {
		console.error("Error fetching member:", error);
		throw new Error("Member not found");
	}
};

router.post("/rename", async (req: Request, res: Response) => {
	const { newName, memberId } = req.body;
	if (typeof newName !== "string" || !memberId) {
		res.status(400).json({ error: "Invalid or missing newName or memberId" });
		return;
	}
	try {
		const member = await getMember(memberId);
		await member.setNickname(newName);
		console.log(`Member ${member.id} renamed to ${newName}`);
		res.status(200).json({ message: "Member renamed successfully" });
	} catch (error) {
		console.error("Error renaming member:", error);
		res.status(500).json({ error: "Failed to rename member" });
	}
});

const handleRoleChange = (action: "add" | "remove") => async (req: Request, res: Response) => {
	const { roleIds, memberId } = req.body;
	if (!Array.isArray(roleIds) || !memberId) {
		res.status(400).json({ error: "Invalid or missing roleIds or memberId" });
		return;
	}
	try {
		const member = await getMember(memberId);

		const currentRoleIds = member.roles.cache.map((role) => role.id);
		const filteredRoleIds =
			action === "add"
				? roleIds.filter((id: string) => !currentRoleIds.includes(id))
				: roleIds.filter((id: string) => currentRoleIds.includes(id));
		if (filteredRoleIds.length === 0) {
			res.status(200).json({ message: `No roles to ${action}` });
			return;
		}

		await member.roles[action](roleIds);
		res.status(200).json({ message: `Roles ${action}ed successfully` });
	} catch (error) {
		console.error(`Error ${action}ing roles:`, error);
		res.status(500).json({ error: `Failed to ${action} roles` });
	}
};

router.post("/add-role", handleRoleChange("add"));
router.post("/remove-role", handleRoleChange("remove"));

export default router;
