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 { validateZod, validateQueryZod } from '#middlewares/validators';
import { {{ modelUpperCase }}CreateBodySchema } from '#contracts/{{ domainPath }}{{ modelKebabCase }}/schema';
import { QueryParamsSchema } from '#contracts/shared';
import { sendSuccess } from '#utils/responseUtils';

export default (_express: Application) => {
	const {{ modelLowerCase }}Provider = new {{ modelUpperCase }}Provider();
	return <Resource>{
{{^isBulk}}
		get: {
			middleware: [verify, requireAdmin, validateQueryZod(QueryParamsSchema), queryModifier],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await {{ modelLowerCase }}Provider.getAll(req.payload || {});
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
{{/isBulk}}
		post: {
			middleware: [verify, requireAdmin, validateZod({{ modelUpperCase }}CreateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
{{#isBulk}}
					const data = await {{ modelLowerCase }}Provider.bulkCreate(req.body.map((b: object) => ({ ...b, created_by: req.user?.id || null })));
{{/isBulk}}{{^isBulk}}
					const data = await {{ modelLowerCase }}Provider.create({ ...req.body, created_by: req.user?.id || null });
{{/isBulk}}
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
