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

export default (_express: Application) => {
	const roleProvider = new RoleProvider();
	return <Resource>{
		get: {
			middleware: [verify, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await roleProvider.getById({ id: req.params.id as string });
					if (!data) {
						throw new Error('Role not found');
					}
					return sendSuccess(res, data.toJSON());
				} catch (error) {
					return res.error(error);
				}
			},
		},
		put: {
			middleware: [verify, queryModifier, validateId, validateZod(RoleMutateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await roleProvider.put(req.params.id as string, {
						...req.body,
						updated_at: new Date(),
						updated_by: req.user?.id || null,
					});
					return sendSuccess(res, data.toJSON());
				} catch (error) {
					return res.error(error);
				}
			},
		},
		delete: {
			middleware: [verify, queryModifier, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					await roleProvider.delete(req.params.id as string);
					return sendSuccess(res, true);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
