import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { Req, Res } from '#interfaces/IApi';
import verify from '#middlewares/auth';
import { requireAdmin } from '#middlewares/auth';
import { auditAccessLogger } from '#middlewares/audit-access-logger';
import { AuditLogService } from '#services/audit/auditLogService';
import { sendSuccess } from '#utils/responseUtils';
import { EntityChangeHistoryQuerySchema } from '#contracts/audit/schema';

export default (_express: Application) => {
	return <Resource>{
		get: {
			middleware: [verify, requireAdmin, auditAccessLogger('VIEWED')],
			handler: async (req: Req, res: Res) => {
				try {
					// Parse query params with schema validation
					const query = EntityChangeHistoryQuerySchema.parse(req.query);
					const { entity_type, entity_id, page = 1, pageSize = 10, sortField, sortOrder } = query;

					const changes = await AuditLogService.getEntityChangeHistory(entity_type, entity_id, {
						page,
						pageSize,
						sortField: sortField || 'created_at',
						sortOrder: sortOrder?.toUpperCase() as 'ASC' | 'DESC' | undefined,
					});

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