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 { validateId } from '#middlewares/validators';
import { validateZod } from '#middlewares/validators';
import { UserRoleMutateBodySchema } from '#contracts/user/schema';
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, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await userRoleProvider.getById({
						id: req.params.id as string,
						includeModels: [
							{ 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'] },
						],
					});
					if (!data) {
						throw new Error('User role not found');
					}
					return sendSuccess(res, data.toJSON());
				} catch (error) {
					return res.error(error);
				}
			},
		},
		put: {
			middleware: [verify, requireAdmin, queryModifier, validateId, validateZod(UserRoleMutateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const existing = await userRoleProvider.getById({ id: req.params.id as string });
					const data = await userRoleProvider.put(req.params.id as string, {
						...req.body,
						updated_at: new Date(),
					});
					// LOGIC-HIGH-03: Invalidate permission cache when user role is updated
					if (existing?.user_id) {
						await invalidatePermissionsCache(existing.user_id).catch(() => {});
					}
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		delete: {
			middleware: [verify, requireAdmin, queryModifier, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const existing = await userRoleProvider.getById({ id: req.params.id as string });
					const data = await userRoleProvider.delete(req.params.id as string);
					// LOGIC-HIGH-03: Invalidate permission cache when user role is revoked
					if (existing?.user_id) {
						await invalidatePermissionsCache(existing.user_id).catch(() => {});
					}
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
