import type { Request, Response } from "express";
import { Router } from "express";
import { db } from "../../../../pkg/db/db.js";
import { user } from "../../../../pkg/db/schema/auth-schema.js";
import { userRoles } from "../../../../pkg/db/schema/user_roles.js";
import { tryCatch } from "../../../../pkg/utils/tryCatch.js";

const router = Router();

router.post("/", async (req: Request, res: Response) => {
	// should get all users
	const { data: users, error: userError } = await tryCatch(
		db.select().from(user),
	);

	if (userError) {
		return res.status(500).json({
			success: false,
			message: "Failed to get users",
			error: userError,
		});
	}
	// should get all roles

	const { data: userRole, error: userRoleError } = await tryCatch(
		db.select().from(userRoles),
	);

	if (userRoleError) {
		return res.status(500).json({
			success: false,
			message: "Failed to get userRoless",
			error: userRoleError,
		});
	}

	// add the roles and return

	const usersWithRoles = users.map((user) => {
		const roles = userRole
			.filter((ur) => ur.userId === user.id)
			.map((ur) => ({ module: ur.module, role: ur.role }));

		return { ...user, roles };
	});

	return res
		.status(200)
		.json({ success: true, message: "User data", data: usersWithRoles });
});

export default router;
