import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { IncidentTypeProvider } from '#providers/IncidentTypeProvider';
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 { IncidentTypeCreateBodySchema } from '#contracts/incident-type/schema';
import { QueryParamsSchema } from '#contracts/shared';
import { sendSuccess } from '#utils/responseUtils';

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