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

export default (_express: Application) => {
	const roleProvider = new RoleProvider();
	return <Resource>{
		get: {
			middleware: [verify, requireAdmin, validateQueryZod(QueryParamsSchema), queryModifier],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await roleProvider.getAll(req.payload || {});
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		post: {
			middleware: [verify, requireAdmin, validateZod(RoleMutateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await roleProvider.create({
						...req.body,
						created_at: new Date(),
						created_by: req.user?.id || null,
					});
					return sendSuccess(res, data.toJSON());
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
