import { z } from 'zod';
import { type OpenAPIRegistry } from '@asteasolutions/zod-to-openapi';
import {
	AuditLogQuerySchema,
	AuditLogListResponseSchema,
	AuditLogByIdResponseSchema,
	DeadLetterQuerySchema,
	DeadLetterListResponseSchema,
	DeadLetterReplayResponseSchema,
	AuditExportQuerySchema,
	AuditExportResponseSchema,
	EntityChangeHistoryQuerySchema,
	EntityChangeHistoryResponseSchema,
} from '#contracts/audit/schema';

export function registerAuditPaths(registry: OpenAPIRegistry): void {
	// -------------------------------------------------------------------------
	// GET /api/v1/audit-logs
	// -------------------------------------------------------------------------
	registry.registerPath({
		method: 'get',
		path: '/api/v1/audit-logs',
		operationId: 'getAuditLogs',
		tags: ['AuditLogs'],
		summary: 'Query system audit logs',
		description: `Retrieve system audit logs with optional filters for pagination and search.

**Available filters:**
- \`actor_id==<uuid>\` - Filter by actor (user) who performed the action
- \`module==<string>\` - Filter by module/feature area (e.g., CRM, RESIDENT, AUTH)
- \`action==<string>\` - Filter by specific action (e.g., CREATE_RESIDENT, DELETE_RESIDENT)
- \`severity==LOW|MEDIUM|HIGH|CRITICAL\` - Filter by severity level
- \`created_at>=<datetime>\` - Filter logs created after this date
- \`created_at<=<datetime>\` - Filter logs created before this date
- \`description==<string>\` - Filter by description text

**Examples:**
- \`filters=actor_id==123e4567-e89b-12d3-a456-426614174000\`
- \`filters=module==CRM,action==CREATE_RESIDENT\`
- \`filters=severity==HIGH,created_at>=2024-01-01T00:00:00Z,created_at<=2024-12-31T23:59:59Z\`

**Note:** Use comma (,) to separate multiple filter conditions (AND logic). Use pipe (|) for OR logic.

Visit https://www.npmjs.com/package/sequelize-api-paginate for full filter syntax.`,
		security: [{ BearerAuth: [] }],
		request: {
			query: AuditLogQuerySchema,
		},
		responses: {
			200: {
				description: 'Audit logs retrieved successfully',
				content: { 'application/json': { schema: AuditLogListResponseSchema } },
			},
			400: { description: 'Bad Request' },
			401: { description: 'Unauthorized' },
			403: { description: 'Forbidden - Admin only' },
		},
	});

	// -------------------------------------------------------------------------
	// GET /api/v1/audit-logs/by-batch/{batch_id}
	// -------------------------------------------------------------------------
	registry.registerPath({
		method: 'get',
		path: '/api/v1/audit-logs/by-batch/{batch_id}',
		operationId: 'getAuditLogsByBatchId',
		tags: ['AuditLogs'],
		summary: 'Get audit logs by batch ID',
		description: 'Retrieve all audit logs associated with a specific batch ID (for bulk operations)',
		security: [{ BearerAuth: [] }],
		request: {
			params: z.object({
				batch_id: z.string().uuid().openapi({ example: '123e4567-e89b-12d3-a456-426614174000' }),
			}),
		},
		responses: {
			200: {
				description: 'Audit logs retrieved successfully',
				content: { 'application/json': { schema: AuditLogByIdResponseSchema } },
			},
			400: { description: 'Bad Request' },
			401: { description: 'Unauthorized' },
			403: { description: 'Forbidden - Admin only' },
		},
	});

	// -------------------------------------------------------------------------
	// GET /api/v1/audit-logs/by-trace/{trace_id}
	// -------------------------------------------------------------------------
	registry.registerPath({
		method: 'get',
		path: '/api/v1/audit-logs/by-trace/{trace_id}',
		operationId: 'getAuditLogsByTraceId',
		tags: ['AuditLogs'],
		summary: 'Get audit logs by trace ID',
		description: 'Retrieve all audit logs associated with a specific trace ID (for workflow correlation)',
		security: [{ BearerAuth: [] }],
		request: {
			params: z.object({
				trace_id: z.string().uuid().openapi({ example: '123e4567-e89b-12d3-a456-426614174000' }),
			}),
		},
		responses: {
			200: {
				description: 'Audit logs retrieved successfully',
				content: { 'application/json': { schema: AuditLogByIdResponseSchema } },
			},
			400: { description: 'Bad Request' },
			401: { description: 'Unauthorized' },
			403: { description: 'Forbidden - Admin only' },
		},
	});

	// -------------------------------------------------------------------------
	// GET /api/v1/audit-dead-letters
	// -------------------------------------------------------------------------
	registry.registerPath({
		method: 'get',
		path: '/api/v1/audit-dead-letters',
		operationId: 'getAuditDeadLetters',
		tags: ['AuditLogs'],
		summary: 'List dead letter queue',
		description: `Retrieve failed audit events from the dead letter queue for investigation.

**Available filters:**
- \`event_type==<string>\` - Filter by event type (e.g., SYSTEM_AUDIT, ENTITY_CHANGE)
- \`investigation_status==PENDING|INVESTIGATING|RESOLVED|IGNORED\` - Filter by investigation status

**Examples:**
- \`filters=event_type==SYSTEM_AUDIT\`
- \`filters=investigation_status==PENDING\`
- \`filters=event_type==SYSTEM_AUDIT,investigation_status==PENDING\`

**Note:** Use comma (,) to separate multiple filter conditions (AND logic). Use pipe (|) for OR logic.

Visit https://www.npmjs.com/package/sequelize-api-paginate for full filter syntax.`,
		security: [{ BearerAuth: [] }],
		request: {
			query: DeadLetterQuerySchema,
		},
		responses: {
			200: {
				description: 'Dead letter queue retrieved successfully',
				content: { 'application/json': { schema: DeadLetterListResponseSchema } },
			},
			400: { description: 'Bad Request' },
			401: { description: 'Unauthorized' },
			403: { description: 'Forbidden - Super Admin only' },
		},
	});

	// -------------------------------------------------------------------------
	// POST /api/v1/audit-dead-letters/{id}/replay
	// -------------------------------------------------------------------------
	registry.registerPath({
		method: 'post',
		path: '/api/v1/audit-dead-letters/{id}/replay',
		operationId: 'replayAuditDeadLetter',
		tags: ['AuditLogs'],
		summary: 'Replay dead letter event',
		description: 'Re-enqueue a failed audit event from the dead letter queue to the outbox for retry',
		security: [{ BearerAuth: [] }],
		request: {
			params: z.object({
				id: z.string().uuid().openapi({ example: '123e4567-e89b-12d3-a456-426614174000' }),
			}),
		},
		responses: {
			200: {
				description: 'Event replayed successfully',
				content: { 'application/json': { schema: DeadLetterReplayResponseSchema } },
			},
			400: { description: 'Bad Request' },
			401: { description: 'Unauthorized' },
			403: { description: 'Forbidden - Super Admin only' },
			404: { description: 'Dead letter record not found' },
		},
	});

	// -------------------------------------------------------------------------
	// GET /api/v1/audit-logs/export/csv
	// -------------------------------------------------------------------------
	registry.registerPath({
		method: 'get',
		path: '/api/v1/audit-logs/export/csv',
		operationId: 'exportAuditLogsToCsv',
		tags: ['AuditLogs'],
		summary: 'Export audit logs to CSV',
		description: `Export system audit logs to CSV format with optional filters.

**Available filters:**
- \`actor_id==<uuid>\` - Filter by actor (user) who performed the action
- \`module==<string>\` - Filter by module/feature area (e.g., CRM, RESIDENT, AUTH)
- \`action==<string>\` - Filter by specific action (e.g., CREATE_RESIDENT, DELETE_RESIDENT)
- \`severity==LOW|MEDIUM|HIGH|CRITICAL\` - Filter by severity level
- \`created_at>=<datetime>\` - Filter logs created after this date
- \`created_at<=<datetime>\` - Filter logs created before this date

**Examples:**
- \`filters=actor_id==123e4567-e89b-12d3-a456-426614174000\`
- \`filters=module==CRM,action==CREATE_RESIDENT\`
- \`filters=severity==HIGH,created_at>=2024-01-01T00:00:00Z,created_at<=2024-12-31T23:59:59Z\`

**Note:** Use comma (,) to separate multiple filter conditions (AND logic). Use pipe (|) for OR logic.

**Safety limit:** Maximum 10,000 records per export (use maxRecords parameter to adjust).

Visit https://www.npmjs.com/package/sequelize-api-paginate for full filter syntax.`,
		security: [{ BearerAuth: [] }],
		request: {
			query: AuditExportQuerySchema,
		},
		responses: {
			200: {
				description: 'CSV file generated successfully',
				content: {
					'application/json': { schema: AuditExportResponseSchema },
					'text/csv': {
						schema: z.string().openapi({ type: 'string', format: 'binary' }),
					},
				},
			},
			400: { description: 'Bad Request' },
			401: { description: 'Unauthorized' },
			403: { description: 'Forbidden - Admin only' },
		},
	});

	// -------------------------------------------------------------------------
	// GET /api/v1/audit-logs/entity-change-history
	// -------------------------------------------------------------------------
	registry.registerPath({
		method: 'get',
		path: '/api/v1/audit-logs/entity-change-history',
		operationId: 'getEntityChangeHistory',
		tags: ['AuditLogs'],
		summary: 'Get entity change history',
		description:
			'Retrieve the change history for a specific entity (e.g., Resident, Contract) showing all modifications made over time.',
		security: [{ BearerAuth: [] }],
		request: {
			query: EntityChangeHistoryQuerySchema,
		},
		responses: {
			200: {
				description: 'Entity change history retrieved successfully',
				content: { 'application/json': { schema: EntityChangeHistoryResponseSchema } },
			},
			400: { description: 'Bad Request' },
			401: { description: 'Unauthorized' },
			403: { description: 'Forbidden - Admin only' },
		},
	});
}
