import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { {{ modelUpperCase }}Provider } from '#providers/{{ modelUpperCase }}Provider';
import { Req, Res } from '#interfaces/IApi';
import { queryModifier } from '#middlewares/query-modifier';
import verify, { requireAdmin } from '#middlewares/auth';
import { validateId } from '#middlewares/validators';
import { validateZod } from '#middlewares/validators';
import { {{ modelUpperCase }}UpdateBodySchema } from '#contracts/{{ domainPath }}{{ modelKebabCase }}/schema';
import { Errors } from '#interfaces/error';
import { sendSuccess } from '#utils/responseUtils';

export default (_express: Application) => {
	const {{ modelLowerCase }}Provider = new {{ modelUpperCase }}Provider();
	return <Resource>{
		get: {
			middleware: [verify, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const isAdmin = req.user?.roles?.some((r) => ['admin', 'system_admin'].includes(r));
					if (!isAdmin && req.user?.id !== req.params.id) {
						throw Errors.forbidden();
					}
					const data = await {{ modelLowerCase }}Provider.getById({ id: req.params.id! });
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		put: {
			middleware: [verify, queryModifier, validateId, validateZod({{ modelUpperCase }}UpdateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const isAdmin = req.user?.roles?.some((r) => ['admin', 'system_admin'].includes(r));
					if (!isAdmin && req.user?.id !== req.params.id) {
						throw Errors.forbidden();
					}
					const data = await {{ modelLowerCase }}Provider.put(req.params.id!, {
						...req.body,
						updated_at: new Date(),
						updated_by: req.user?.id || null,
					});
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		delete: {
			middleware: [verify, requireAdmin, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await {{ modelLowerCase }}Provider.delete(req.params.id!);
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};