import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { ApprovalManager } from './approval-manager.js';
let approvalManager;
export async function setupApprovalSystem(server, configManager) {
    approvalManager = new ApprovalManager(configManager);
    await approvalManager.init();
    // Add approval-specific tool handlers
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
        const { name, arguments: args } = request.params;
        if (!args) {
            throw new Error('No arguments provided');
        }
        switch (name) {
            case 'request_approval': {
                const { toolName, action, parameters, userId, ttl } = args;
                const approvalRequest = await approvalManager.createApprovalRequest({
                    toolName,
                    action,
                    parameters,
                    userId,
                    ttl
                });
                if (!approvalRequest) {
                    return {
                        content: [{
                                type: 'text',
                                text: '✅ Action auto-approved based on policy conditions'
                            }],
                        structured: { autoApproved: true }
                    };
                }
                return {
                    content: [{
                            type: 'text',
                            text: `🔐 Approval Required

**Tool**: ${toolName}
**Action**: ${action}
**Risk Level**: ${approvalRequest.riskLevel}
**Impact**: ${approvalRequest.impact.join(', ')}
**Reversible**: ${approvalRequest.reversible ? 'Yes' : 'No'}
**Expires**: ${approvalRequest.expiresAt.toLocaleString()}

Request ID: ${approvalRequest.id}

Use \`approve_request\` or \`reject_request\` with this ID to respond.`
                        }],
                    structured: approvalRequest
                };
            }
            case 'approve_request': {
                const { requestId, userId } = args;
                const success = await approvalManager.approveRequest(requestId, userId);
                if (!success) {
                    return {
                        content: [{
                                type: 'text',
                                text: '❌ Failed to approve request. It may have expired or already been processed.'
                            }]
                    };
                }
                return {
                    content: [{
                            type: 'text',
                            text: '✅ Request approved successfully'
                        }],
                    structured: { approved: true, requestId }
                };
            }
            case 'reject_request': {
                const { requestId, userId, reason } = args;
                const success = await approvalManager.rejectRequest(requestId, userId, reason);
                if (!success) {
                    return {
                        content: [{
                                type: 'text',
                                text: '❌ Failed to reject request. It may have expired or already been processed.'
                            }]
                    };
                }
                return {
                    content: [{
                            type: 'text',
                            text: '❌ Request rejected successfully'
                        }],
                    structured: { rejected: true, requestId, reason }
                };
            }
            case 'list_pending_approvals': {
                const { userId } = args;
                const pendingRequests = await approvalManager.getPendingRequests(userId);
                if (pendingRequests.length === 0) {
                    return {
                        content: [{
                                type: 'text',
                                text: '📭 No pending approval requests'
                            }]
                    };
                }
                const requestList = pendingRequests.map(r => `• **${r.toolName}/${r.action}** (${r.riskLevel} risk)
  - Requested by: ${r.requestedBy}
  - Expires: ${r.expiresAt.toLocaleString()}
  - ID: ${r.id}`).join('\n\n');
                return {
                    content: [{
                            type: 'text',
                            text: `📋 Pending Approval Requests:\n\n${requestList}`
                        }],
                    structured: pendingRequests
                };
            }
            case 'get_approval_audit_log': {
                const { startDate, endDate, userId, toolName, result } = args;
                const filters = {
                    startDate: startDate ? new Date(startDate) : undefined,
                    endDate: endDate ? new Date(endDate) : undefined,
                    userId,
                    toolName,
                    result
                };
                const logs = await approvalManager.getAuditLog(filters);
                if (logs.length === 0) {
                    return {
                        content: [{
                                type: 'text',
                                text: '📭 No audit log entries found'
                            }]
                    };
                }
                const logEntries = logs.slice(0, 50).map(l => `• ${l.timestamp.toLocaleString()} - ${l.userId} ${l.result} ${l.toolName}/${l.action}`).join('\n');
                return {
                    content: [{
                            type: 'text',
                            text: `📜 Audit Log (last ${Math.min(logs.length, 50)} entries):\n\n${logEntries}`
                        }],
                    structured: logs
                };
            }
        }
    });
    // Return tool definitions
    return {
        tools: [
            {
                name: 'request_approval',
                description: 'Request approval for a high-risk operation',
                inputSchema: {
                    type: 'object',
                    properties: {
                        toolName: { type: 'string', description: 'Name of the tool requesting approval' },
                        action: { type: 'string', description: 'Action to be performed' },
                        parameters: { type: 'object', description: 'Parameters for the action' },
                        userId: { type: 'string', description: 'ID of the user making the request' },
                        ttl: { type: 'number', description: 'Time to live in seconds (optional)' }
                    },
                    required: ['toolName', 'action', 'parameters', 'userId']
                }
            },
            {
                name: 'approve_request',
                description: 'Approve a pending request',
                inputSchema: {
                    type: 'object',
                    properties: {
                        requestId: { type: 'string', description: 'ID of the request to approve' },
                        userId: { type: 'string', description: 'ID of the user approving' }
                    },
                    required: ['requestId', 'userId']
                }
            },
            {
                name: 'reject_request',
                description: 'Reject a pending request',
                inputSchema: {
                    type: 'object',
                    properties: {
                        requestId: { type: 'string', description: 'ID of the request to reject' },
                        userId: { type: 'string', description: 'ID of the user rejecting' },
                        reason: { type: 'string', description: 'Reason for rejection (optional)' }
                    },
                    required: ['requestId', 'userId']
                }
            },
            {
                name: 'list_pending_approvals',
                description: 'List all pending approval requests',
                inputSchema: {
                    type: 'object',
                    properties: {
                        userId: { type: 'string', description: 'Filter by user (optional)' }
                    },
                    required: []
                }
            },
            {
                name: 'get_approval_audit_log',
                description: 'Get audit log of approval decisions',
                inputSchema: {
                    type: 'object',
                    properties: {
                        startDate: { type: 'string', description: 'Start date (ISO format)' },
                        endDate: { type: 'string', description: 'End date (ISO format)' },
                        userId: { type: 'string', description: 'Filter by user' },
                        toolName: { type: 'string', description: 'Filter by tool' },
                        result: { type: 'string', enum: ['approved', 'rejected', 'auto_approved', 'expired'] }
                    },
                    required: []
                }
            }
        ]
    };
}
export function getApprovalManager() {
    return approvalManager;
}
//# sourceMappingURL=index.js.map