import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { AuditDeadLetter } from '#models/AuditDeadLetter';
import { AuditOutbox } from '#models/AuditOutbox';
import { randomUUID } from 'crypto';
import { Req, Res } from '#interfaces/IApi';
import verify from '#middlewares/auth';
import { requireSuperAdmin } from '#middlewares/auth';
import { auditAccessLogger } from '#middlewares/audit-access-logger';
import { sendSuccess } from '#utils/responseUtils';
import Logger from '#utils/logger';
import auditMetrics from '#utils/auditMetrics';

export default (_express: Application) => {
	return <Resource>{
		post: {
			middleware: [verify, requireSuperAdmin, auditAccessLogger('EXPORTED')],
			handler: async (req: Req, res: Res) => {
				try {
					const { id } = req.params;

					// Get dead letter record
					const deadLetter = await AuditDeadLetter.findByPk(id);
					if (!deadLetter) {
						return res.status(404).json({ error: 'Dead letter record not found' });
					}

					// Check replay limit (max 3 replays)
					const MAX_REPLAY_COUNT = 3;
					const currentReplayCount = deadLetter.replay_count || 0;
					if (currentReplayCount >= MAX_REPLAY_COUNT) {
						return res.status(400).json({
							error: 'Maximum replay limit reached',
							message: `This event has been replayed ${currentReplayCount} times. Maximum allowed is ${MAX_REPLAY_COUNT}.`,
						});
					}

					// Re-enqueue the event to outbox
					const newOutboxEventId = randomUUID();
					await AuditOutbox.create({
						id: newOutboxEventId,
						request_id: randomUUID(),
						trace_id: randomUUID(),
						event_type: deadLetter.event_type,
						payload: deadLetter.original_payload,
						payload_size: JSON.stringify(deadLetter.original_payload).length,
						status: 'PENDING',
						retry_count: 0,
						max_retries: 3,
						created_at: new Date(),
						updated_at: new Date(),
					});

					// Update dead letter record
					await deadLetter.update({
						replayed: true,
						replayed_at: new Date(),
						replay_count: currentReplayCount + 1,
						investigation_status: 'RESOLVED',
						resolution_notes: 'Event replayed successfully',
					});

					Logger.info(`Replayed audit event ${id} as new outbox event ${newOutboxEventId}`);

					// Record metric
					try {
						auditMetrics.auditDeadLetterReplays.inc({ event_type: deadLetter.event_type, success: 'true' });
					} catch {
						// Metrics optional, don't fail if not available
					}

					return sendSuccess(res, {
						message: 'Event replayed successfully',
						new_outbox_event_id: newOutboxEventId,
						replay_count: currentReplayCount + 1,
					});
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
