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

export default (_express: Application) => {
	return <Resource>{
		get: {
			middleware: [verify, requireSuperAdmin, queryModifier, auditAccessLogger('VIEWED')],
			handler: async (req: Req, res: Res) => {
				try {
					const where: any = {};
					// queryModifier middleware will parse filters and apply them via req.payload.filters
					if (req.payload?.filters) {
						Object.assign(where, req.payload.filters);
					}

					const { page = 1, pageSize = 50, sortField, sortOrder } = req.payload || {};

					// Validate sortField to prevent SQL injection
					const allowedSortFields = ['failed_at', 'event_type', 'investigation_status', 'replayed'];
					const validSortField = allowedSortFields.includes(sortField || '') ? sortField : 'failed_at';
					const validSortOrder = sortOrder === 'ASC' ? 'ASC' : 'DESC';

					const order: any = [[validSortField, validSortOrder]];

					const offset = (page - 1) * pageSize;

					const { count, rows } = await AuditDeadLetter.findAndCountAll({
						where,
						order,
						limit: pageSize,
						offset,
					});

					return sendSuccess(res, {
						count,
						rows,
						page,
						pageSize,
					});
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
