import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { UserRoleProvider } from '#providers/UserRoleProvider';
import { Req, Res } from '#interfaces/IApi';
import { queryModifier } from '#middlewares/query-modifier';
import verify, { requireAdmin, invalidatePermissionsCache } from '#middlewares/auth';
import { validateZod, validateQueryZod } from '#middlewares/validators';
import { UserRoleMutateBodySchema } from '#contracts/user/schema';
import { QueryParamsSchema } from '#contracts/shared';
import { User } from '#models/User';
import { Role } from '#models/Role';
import { sendSuccess } from '#utils/responseUtils';

export default (_express: Application) => {
	const userRoleProvider = new UserRoleProvider();
	return <Resource>{
		get: {
			middleware: [verify, requireAdmin, validateQueryZod(QueryParamsSchema), queryModifier],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await userRoleProvider.getAll({
						...req.payload,
						include: [
							{ model: User, as: 'user', attributes: ['id', 'email', 'first_name', 'last_name'] },
							{ model: Role, as: 'role', attributes: ['id', 'name', 'description'] },
							{ model: User, as: 'assigned_by_user', attributes: ['id', 'email', 'first_name', 'last_name'] },
						],
					});
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		post: {
			middleware: [verify, requireAdmin, queryModifier, validateZod(UserRoleMutateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await userRoleProvider.create({
						...req.body,
						assigned_at: new Date(),
						assigned_by: req.user?.id || null,
					});
					// LOGIC-HIGH-03: Invalidate permission cache when role is assigned to user
					if (data.user_id) {
						await invalidatePermissionsCache(data.user_id).catch(() => {});
					}
					return sendSuccess(res, data.toJSON());
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
