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

export default (_express: Application) => {
	const permissionProvider = new PermissionProvider();
	return <Resource>{
		get: {
			middleware: [verify, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await permissionProvider.getById({ id: req.params.id as string });
					if (!data) {
						throw new Error('Permission not found');
					}
					return sendSuccess(res, data.toJSON());
				} catch (error) {
					return res.error(error);
				}
			},
		},
		put: {
			middleware: [verify, validateId, validateZod(PermissionMutateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await permissionProvider.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, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					await permissionProvider.delete(req.params.id as string);
					return sendSuccess(res, true);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
