"use strict";
/**
 * Workflow Audit System
 * Tracks validation history, changes, and compliance for workflows
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.workflowAudit = void 0;
class WorkflowAudit {
    constructor(maxHistorySize = 1000) {
        this.history = [];
        this.maxHistorySize = maxHistorySize;
    }
    /**
     * Record a validation event
     */
    recordValidation(workflow, validationResult, userId, action, changes, metadata) {
        const entry = {
            timestamp: new Date().toISOString(),
            workflowId: workflow.id,
            workflowVersion: workflow.version,
            validationResult,
            userId,
            action,
            changes,
            metadata: {
                environment: metadata?.environment || 'development',
                browser: metadata?.browser || 'unknown',
                userAgent: metadata?.userAgent || 'unknown',
                ipAddress: metadata?.ipAddress,
            },
        };
        this.history.unshift(entry);
        if (this.history.length > this.maxHistorySize) {
            this.history.pop();
        }
        return entry;
    }
    /**
     * Get validation history for a workflow
     */
    getWorkflowHistory(workflowId) {
        return this.history.filter(entry => entry.workflowId === workflowId);
    }
    /**
     * Get audit summary for a workflow
     */
    getAuditSummary(workflowId) {
        const workflowHistory = this.getWorkflowHistory(workflowId);
        const totalValidations = workflowHistory.length;
        // Calculate success rate
        const successfulValidations = workflowHistory.filter(entry => entry.validationResult.isValid).length;
        const successRate = totalValidations > 0
            ? (successfulValidations / totalValidations) * 100
            : 0;
        // Calculate average issues per validation
        const totalIssues = workflowHistory.reduce((sum, entry) => sum + entry.validationResult.errors.length + entry.validationResult.warnings.length, 0);
        const averageIssues = totalValidations > 0
            ? totalIssues / totalValidations
            : 0;
        // Find most common issues
        const issueCounts = new Map();
        workflowHistory.forEach(entry => {
            [...entry.validationResult.errors, ...entry.validationResult.warnings].forEach(error => {
                const count = issueCounts.get(error.code) || 0;
                issueCounts.set(error.code, count + 1);
            });
        });
        const mostCommonIssues = Array.from(issueCounts.entries())
            .map(([code, count]) => ({
            code,
            count,
            percentage: (count / totalIssues) * 100,
        }))
            .sort((a, b) => b.count - a.count)
            .slice(0, 5);
        // Calculate validation trend
        const trend = this.calculateValidationTrend(workflowHistory);
        // Check compliance status
        const complianceStatus = this.checkComplianceStatus(workflowHistory);
        return {
            totalValidations,
            successRate,
            averageIssuesPerValidation: averageIssues,
            mostCommonIssues,
            validationTrend: trend,
            complianceStatus,
        };
    }
    /**
     * Calculate validation trend over time
     */
    calculateValidationTrend(history) {
        const trendMap = new Map();
        history.forEach(entry => {
            const date = entry.timestamp.split('T')[0];
            const current = trendMap.get(date) || { success: 0, failure: 0 };
            if (entry.validationResult.isValid) {
                current.success++;
            }
            else {
                current.failure++;
            }
            trendMap.set(date, current);
        });
        return Array.from(trendMap.entries())
            .map(([date, counts]) => ({
            date,
            successCount: counts.success,
            failureCount: counts.failure,
        }))
            .sort((a, b) => a.date.localeCompare(b.date));
    }
    /**
     * Check compliance status based on validation history
     */
    checkComplianceStatus(history) {
        const latestEntry = history[0];
        if (!latestEntry) {
            return {
                security: false,
                admin: false,
                data: false,
                lastChecked: new Date().toISOString(),
            };
        }
        const { validationResult } = latestEntry;
        const errors = validationResult.errors;
        const hasSecurityIssues = errors.some(error => error.code.startsWith('INVALID_SECURITY_') ||
            error.code === 'INSECURE_CONNECTION');
        const hasAdminIssues = errors.some(error => error.code.startsWith('INVALID_APPROVAL_') ||
            error.code === 'INVALID_APPROVER');
        const hasDataIssues = errors.some(error => error.code === 'INVALID_CONFIG_VALUE' ||
            error.code === 'MISSING_REQUIRED_CONFIG');
        return {
            security: !hasSecurityIssues,
            admin: !hasAdminIssues,
            data: !hasDataIssues,
            lastChecked: latestEntry.timestamp,
        };
    }
    /**
     * Export audit data for compliance reporting
     */
    exportAuditData(workflowId) {
        const history = this.getWorkflowHistory(workflowId);
        const summary = this.getAuditSummary(workflowId);
        return JSON.stringify({
            workflowId,
            summary,
            history,
            exportDate: new Date().toISOString(),
            version: '1.0',
        }, null, 2);
    }
    /**
     * Clear audit history (useful for testing)
     */
    clearHistory() {
        this.history = [];
    }
}
// Create singleton instance
exports.workflowAudit = new WorkflowAudit();
//# sourceMappingURL=workflowAudit.js.map