"use strict";
/**
 * Contradiction Resolution — Resolves conflicting findings on the same route/file.
 *
 * Key contradiction types:
 * 1. Same route has both "protected by middleware" (info) AND "missing auth" (high/critical)
 *    → Keep only the info-level "protected by middleware" finding
 * 2. Same file has BYOK "transient use" (info) AND "key stored insecurely" (high)
 *    → Keep only the most accurate one based on context
 * 3. Same line has conflicting severities from different layers
 *    → Prefer the lower severity if one explicitly notes protection
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveContradictions = resolveContradictions;
const middleware_detector_1 = require("../model/middleware-detector");
/**
 * Resolve contradictions in findings
 */
function resolveContradictions(vulnerabilities, middlewareConfig) {
    // Group findings by file path for contradiction analysis
    const byFile = new Map();
    for (const vuln of vulnerabilities) {
        const existing = byFile.get(vuln.filePath) || [];
        existing.push(vuln);
        byFile.set(vuln.filePath, existing);
    }
    const result = [];
    for (const [filePath, fileVulns] of byFile) {
        // Check for auth contradictions in this file
        const authFindings = fileVulns.filter(v => v.category === 'missing_auth');
        const otherFindings = fileVulns.filter(v => v.category !== 'missing_auth');
        // Identify protected routes (middleware or auth helper)
        const protectedInfos = authFindings.filter(v => v.severity === 'info' &&
            (v.validationNotes === 'MIDDLEWARE_PROTECTED' ||
                v.validationNotes === 'AUTH_HELPER_PROTECTED' ||
                v.title.includes('protected by middleware') ||
                v.title.includes('uses auth helper')));
        // NEW: Check if this file's route is protected by middleware (even without explicit info finding)
        // This catches Layer 3 findings that don't have the Layer 2 protection info
        const routePath = (0, middleware_detector_1.getRoutePathFromFile)(filePath);
        const isAPIRouteProtected = routePath && middlewareConfig?.hasAuthMiddleware
            ? (0, middleware_detector_1.isRouteProtectedByMiddleware)(routePath, middlewareConfig).isProtected
            : false;
        // Also check if file is a client component calling protected API routes
        // Client components (components/, app/ without route.ts) calling /api/** are safe
        const isClientCallingProtectedAPI = middlewareConfig?.hasAuthMiddleware &&
            (filePath.includes('/components/') ||
                (filePath.includes('/app/') && !filePath.includes('route.ts')));
        // If we have protected route info findings OR the route is protected by middleware
        if (protectedInfos.length > 0 || isAPIRouteProtected || isClientCallingProtectedAPI) {
            // Keep the protected info findings
            result.push(...protectedInfos);
            // For other auth findings on same file, either drop or downgrade to info
            const otherAuthFindings = authFindings.filter(v => !protectedInfos.includes(v));
            for (const vuln of otherAuthFindings) {
                // If it's high/critical missing auth on a protected route, drop it entirely
                // (the middleware/helper protection supersedes)
                if (vuln.severity === 'critical' || vuln.severity === 'high') {
                    continue; // Skip this finding
                }
                // Keep lower severity auth findings as-is
                result.push(vuln);
            }
        }
        else {
            // No protection detected - keep all auth findings as-is
            result.push(...authFindings);
        }
        // Handle BYOK contradictions
        const byokFindings = otherFindings.filter(v => v.category === 'ai_pattern' && v.title.toLowerCase().includes('byok'));
        const nonByokFindings = otherFindings.filter(v => !(v.category === 'ai_pattern' && v.title.toLowerCase().includes('byok')));
        if (byokFindings.length > 0) {
            // Check if we have both transient (low) and storage (high) BYOK findings
            const transientByok = byokFindings.filter(v => v.severity === 'low' || v.severity === 'info');
            const storageByok = byokFindings.filter(v => v.severity === 'high' || v.severity === 'medium');
            if (transientByok.length > 0 && storageByok.length > 0) {
                // If we detected transient usage, prefer the lower severity
                // The higher severity ones may be false positives
                result.push(...transientByok);
                // Mark high-severity BYOK for review
                for (const vuln of storageByok) {
                    result.push({
                        ...vuln,
                        severity: 'low',
                        validationNotes: `${vuln.validationNotes || ''} (downgraded: transient BYOK usage detected in same file)`.trim(),
                    });
                }
            }
            else {
                // Keep all BYOK findings as-is
                result.push(...byokFindings);
            }
        }
        // Add non-BYOK other findings
        result.push(...nonByokFindings);
    }
    return result;
}
//# sourceMappingURL=contradictions.js.map