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 { validateId } from '#middlewares/validators';
import { validateZod } from '#middlewares/validators';
import { IncidentUpdateBodySchema } from '#contracts/incident/schema';
import { Errors } from '#interfaces/error';
import { sendSuccess } from '#utils/responseUtils';
import { AuditLogService } from '#services/audit/auditLogService';

export default (_express: Application) => {
	const incidentProvider = new IncidentProvider();
	return <Resource>{
		get: {
			middleware: [verify, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await incidentProvider.getByIdOptimized(req.params.id!);
					if (!data) {
						throw Errors.notFound('Incident');
					}
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		put: {
			middleware: [verify, queryModifier, validateId, validateZod(IncidentUpdateBodySchema)],
			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 incidentProvider.put(req.params.id!, {
						...req.body,
						updated_at: new Date(),
						updated_by: req.user?.id || null,
					});

					// Audit log for incident update
					await AuditLogService.enqueueEntityChangeFromRequest(req, {
						entityType: 'Incident',
						entityId: data.id,
						changeType: 'UPDATE',
						payload: {
							before: null,
							after: data.toJSON(),
							changed_fields: Object.keys(req.body),
						},
						reason: `Updated incident: ${req.body.title || 'N/A'}`,
					});

					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		delete: {
			middleware: [verify, requireAdmin, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const incident = await incidentProvider.getById({ id: req.params.id! });
					if (!incident) throw Errors.notFound('Incident');

					const data = await incidentProvider.delete(req.params.id!);

					// Audit log for incident deletion
					await AuditLogService.enqueueEntityChangeFromRequest(req, {
						entityType: 'Incident',
						entityId: req.params.id!,
						changeType: 'DELETE',
						payload: {
							before: incident.toJSON(),
							after: null,
							changed_fields: Object.keys(incident.toJSON()),
						},
						reason: `Deleted incident: ${incident.title || 'N/A'}`,
					});

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