import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { IncidentProvider } from '#providers/IncidentProvider';
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 { IncidentCreateBodySchema } from '#contracts/incident/schema';
import { QueryParamsSchema } from '#contracts/shared';
import { sendSuccess } from '#utils/responseUtils';
import { generateIncidentCode } from '#utils/incidentCodeGenerator';
import { AuditLogService } from '#services/audit/auditLogService';

export default (_express: Application) => {
	const incidentProvider = new IncidentProvider();
	return <Resource>{
		get: {
			middleware: [verify, validateQueryZod(QueryParamsSchema), queryModifier],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await incidentProvider.getAllOptimized(req.payload || {}, { user: req.user });
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		post: {
			middleware: [verify, validateZod(IncidentCreateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					// Generate unique code automatically
					const code = await generateIncidentCode();
					const data = await incidentProvider.create({
						...req.body,
						code,
						created_by: req.user?.id || null,
					});

					// Audit log for resident creation
					await AuditLogService.enqueueEntityChangeFromRequest(req, {
						entityType: 'Incident',
						entityId: data.id,
						changeType: 'CREATE',
						payload: {
							before: null,
							after: data.toJSON(),
							changed_fields: Object.keys(req.body),
						},
						reason: `Created new incident: ${req.body.full_name || 'N/A'}`,
					});

					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
