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

export default (_express: Application) => {
	const rolePermissionProvider = new RolePermissionProvider();
	return <Resource>{
		get: {
			middleware: [verify, requireAdmin, validateQueryZod(QueryParamsSchema), queryModifier],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await rolePermissionProvider.getAll({
						...req.payload,
						include: [
							{ model: Role, as: 'role', attributes: ['id', 'name', 'description'] },
							{ model: Permission, as: 'permission', attributes: ['id', 'name', 'description', 'resource', 'action'] },
						],
					});
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
