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",
		"helperCommands",
		"production",
		"quality",
		"eom",
		"forklifts",
	]),
	role: z.enum([
		"systemAdmin",
		"admin",
		"manager",
		"supervisor",
		"tester",
		"user",
		"viewer",
	]),
});

const router = Router();

router.patch("/:userId/grant", 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
			.insert(userRoles)
			.values({
				userId: userId,
				module: validated.module,
				role: validated.role,
			})
			.onConflictDoUpdate({
				target: [userRoles.userId, userRoles.module],
				set: { module: validated.module, role: validated.role },
			});
		log.info(
			{},
			`Module: ${validated.module}, Role: ${validated.role} as was just granted to userID: ${userId}`,
		);
		return res.status(200).json({
			success: true,
			message: `Module: ${validated.module}, Role: ${validated.role} as was just granted`,
			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;
