import { and, eq } from "drizzle-orm";
import type { Request, Response } from "express";
import { Router } from "express";
import z from "zod";
import { db } from "../../../../pkg/db/db.js";
import { userRoles } from "../../../../pkg/db/schema/user_roles.js";
import { createLogger } from "../../../../pkg/logger/logger.js";

const roleSchema = z.object({
	module: z.enum([
		"users",
		"system",
		"ocp",
		"siloAdjustments",
		"demandManagement",
		"logistics",
		"production",
		"quality",
		"eom",
		"forklifts",
	]),
});

const router = Router();

router.patch("/:userId/revoke", async (req: Request, res: Response) => {
	const log = createLogger({
		module: "admin",
		subModule: "grantRoles",
	});
	const userId = req.params.userId;

	try {
		const validated = roleSchema.parse(req.body);

		const data = await db
			.delete(userRoles)
			.where(
				and(
					eq(userRoles.userId, userId),
					eq(userRoles.module, validated.module),
				),
			);
		log.info(
			{},
			`Module: ${validated.module}, was just revoked fron userID: ${userId}`,
		);
		return res.status(200).json({
			success: true,
			message: `Module: ${validated.module}, was just revoked fron userID: ${userId}`,
			data,
		});
	} catch (err) {
		if (err instanceof z.ZodError) {
			const flattened = z.flattenError(err);
			return res.status(400).json({
				error: "Validation failed",
				details: flattened,
			});
		}

		return res.status(400).json({
			success: false,
			message: "Invalid input please try again.",
			error: err,
		});
	}
});

export default router;
