/**
 * Compliance Bundle Tests
 *
 * Tests for universal audit-defensible compliance assessment.
 *
 * @module __tests__/compliance-bundle
 */
import { describe, it, expect } from "vitest";
import { runSingleFrameworkAssessment, runComplianceAssessment, generateComplianceSummary, } from "../compliance/compliance-bundle.js";
import { formatComplianceReportAsMarkdown, formatMultiFrameworkReportAsMarkdown, generateComplianceReport, generateMultiFrameworkReport, } from "../compliance/index.js";
import { FRAMEWORK_ATTESTATIONS, getFrameworkAttestation, formatAttestationAsMarkdown, formatMultiFrameworkAttestationAsMarkdown, } from "../compliance/attestation.js";
// Mock findings for testing
const createMockFindings = () => [
    {
        id: "test-001",
        severity: "high",
        category: "security",
        description: "Hardcoded credentials found",
        confidence: 95,
        evidence: "API key in source code",
        verifications: [],
        created_at: new Date().toISOString(),
        cwe_ids: ["CWE-798"],
    },
    {
        id: "test-002",
        severity: "medium",
        category: "logging",
        description: "Insufficient audit logging",
        confidence: 80,
        evidence: "Missing audit trail for sensitive operations",
        verifications: [],
        created_at: new Date().toISOString(),
    },
    {
        id: "test-003",
        severity: "low",
        category: "encryption",
        description: "Weak cipher suite",
        confidence: 70,
        evidence: "TLS 1.1 still enabled",
        verifications: [],
        created_at: new Date().toISOString(),
    },
];
describe("Framework Attestations", () => {
    it("should have attestations for all standard frameworks", () => {
        const standardFrameworks = [
            "SOC2",
            "ISO27001",
            "PCI-DSS",
            "HIPAA",
            "42-CFR-PART-2",
            "GDPR",
            "NIST-800-53",
            "CIS",
        ];
        for (const framework of standardFrameworks) {
            const attestation = FRAMEWORK_ATTESTATIONS[framework];
            expect(attestation).toBeDefined();
            expect(attestation.fullName).toBeTruthy();
            expect(attestation.methodology.length).toBeGreaterThan(0);
            expect(attestation.scopeLimitations.length).toBeGreaterThan(0);
            expect(attestation.auditorNote).toBeTruthy();
        }
    });
    it("should have attestations for AI frameworks", () => {
        const aiFrameworks = [
            "OWASP-LLM",
            "NIST-AI-RMF",
            "MITRE-ATLAS",
            "EU-AI-ACT",
            "ISO-42001",
        ];
        for (const framework of aiFrameworks) {
            const attestation = FRAMEWORK_ATTESTATIONS[framework];
            expect(attestation).toBeDefined();
            expect(attestation.fullName).toBeTruthy();
            expect(attestation.methodology.length).toBeGreaterThan(0);
            expect(attestation.scopeLimitations.length).toBeGreaterThan(0);
            expect(attestation.auditorNote).toBeTruthy();
        }
    });
    it("should format single-framework attestation as markdown", () => {
        const markdown = formatAttestationAsMarkdown("SOC2");
        expect(markdown).toContain("## Attestation");
        expect(markdown).toContain("SOC 2 Trust Services Criteria");
        expect(markdown).toContain("### Assessment Methodology");
        expect(markdown).toContain("### Scope Limitations");
        expect(markdown).toContain("### Auditor Note");
        expect(markdown).toContain("licensed CPA firm");
    });
    it("should format multi-framework attestation as markdown", () => {
        const markdown = formatMultiFrameworkAttestationAsMarkdown(["SOC2", "ISO27001"]);
        expect(markdown).toContain("## Attestation");
        expect(markdown).toContain("SOC 2 Trust Services Criteria");
        expect(markdown).toContain("ISO/IEC 27001:2022");
        expect(markdown).toContain("### Framework-Specific Notes");
    });
});
describe("Audit-Defensible Report Formatting", () => {
    const mockFindings = createMockFindings();
    it("should format compliance report without audit options (backward compatible)", () => {
        const report = generateComplianceReport(mockFindings, "SOC2", "/test/project");
        const markdown = formatComplianceReportAsMarkdown(report);
        expect(markdown).toContain("# SOC2 Compliance Report");
        expect(markdown).toContain("## Compliance Status");
        // Should NOT have audit sections when no options provided
        expect(markdown).not.toContain("## Audit Trail Integrity");
        expect(markdown).not.toContain("## Evidence Bundle");
        expect(markdown).not.toContain("## Attestation");
    });
    it("should include attestation section when requested", () => {
        const report = generateComplianceReport(mockFindings, "SOC2", "/test/project");
        const options = {
            includeAttestation: true,
        };
        const markdown = formatComplianceReportAsMarkdown(report, options);
        expect(markdown).toContain("## Attestation");
        expect(markdown).toContain("SOC 2 Trust Services Criteria");
        expect(markdown).toContain("### Assessment Methodology");
        expect(markdown).toContain("### Scope Limitations");
    });
    it("should include audit trail section when verification provided", () => {
        const report = generateComplianceReport(mockFindings, "ISO27001", "/test/project");
        const options = {
            auditVerification: {
                projectPath: "/test/project",
                verifiedAt: new Date().toISOString(),
                verified: true,
                totalEntries: 10,
                entriesVerified: 10,
                entriesPassed: 10,
                entriesFailed: 0,
                chainIntegrity: true,
                failures: [],
                genesisHash: "abc123def456789",
                headHash: "xyz789abc123456",
            },
        };
        const markdown = formatComplianceReportAsMarkdown(report, options);
        expect(markdown).toContain("## Audit Trail Integrity");
        expect(markdown).toContain("Verified");
        expect(markdown).toContain("Total Entries | 10");
        expect(markdown).toContain("Chain Integrity | Intact");
        expect(markdown).toContain("Genesis Hash");
    });
    it("should show warning for failed audit verification", () => {
        const report = generateComplianceReport(mockFindings, "PCI-DSS", "/test/project");
        const options = {
            auditVerification: {
                projectPath: "/test/project",
                verifiedAt: new Date().toISOString(),
                verified: false,
                totalEntries: 10,
                entriesVerified: 8,
                entriesPassed: 7,
                entriesFailed: 1,
                chainIntegrity: false,
                failures: [],
                firstFailure: {
                    entryId: "entry-008",
                    timestamp: new Date().toISOString(),
                    hashValid: false,
                    chainValid: false,
                    failureReason: "Hash mismatch",
                },
            },
        };
        const markdown = formatComplianceReportAsMarkdown(report, options);
        expect(markdown).toContain("INTEGRITY FAILURE");
        expect(markdown).toContain("Chain Integrity | Broken");
        expect(markdown).toContain("Audit trail integrity compromised");
    });
    it("should format multi-framework report with audit options", () => {
        const report = generateMultiFrameworkReport(mockFindings, ["SOC2", "ISO27001"], "/test/project");
        const options = {
            includeAttestation: true,
        };
        const markdown = formatMultiFrameworkReportAsMarkdown(report, options);
        expect(markdown).toContain("# Multi-Framework Compliance Report");
        expect(markdown).toContain("## Attestation");
        expect(markdown).toContain("### Framework-Specific Notes");
        expect(markdown).toContain("SOC2:");
        expect(markdown).toContain("ISO27001:");
    });
    it("should add audit-defensible label to footer when features used", () => {
        const report = generateComplianceReport(mockFindings, "HIPAA", "/test/project");
        const options = {
            auditVerification: {
                projectPath: "/test/project",
                verifiedAt: new Date().toISOString(),
                verified: true,
                totalEntries: 5,
                entriesVerified: 5,
                entriesPassed: 5,
                entriesFailed: 0,
                chainIntegrity: true,
                failures: [],
            },
        };
        const markdown = formatComplianceReportAsMarkdown(report, options);
        expect(markdown).toContain("Audit-Defensible");
    });
});
describe("Compliance Assessment Bundle", () => {
    const mockFindings = createMockFindings();
    it("should run single framework assessment without audit features", async () => {
        const result = await runSingleFrameworkAssessment({
            projectPath: "/test/project",
            findings: mockFindings,
            framework: "SOC2",
            collectEvidence: false,
            verifyAuditTrail: false,
            includeAttestation: true,
        });
        expect(result.report).toBeDefined();
        expect(result.report.framework).toBe("SOC2");
        expect(result.markdownReport).toContain("# SOC2 Compliance Report");
        expect(result.markdownReport).toContain("## Attestation");
        expect(result.status).toMatch(/compliant|at_risk|non_compliant/);
        expect(result.evidenceBundle).toBeUndefined();
        expect(result.auditVerification).toBeUndefined();
    });
    it("should run multi-framework assessment", async () => {
        const result = await runComplianceAssessment({
            projectPath: "/test/project",
            findings: mockFindings,
            frameworks: ["SOC2", "ISO27001"],
            collectEvidence: false,
            verifyAuditTrail: false,
            includeAttestation: true,
        });
        expect(result.reports).toBeDefined();
        expect(result.reports["SOC2"]).toBeDefined();
        expect(result.reports["ISO27001"]).toBeDefined();
        expect(result.multiFrameworkReport).toBeDefined();
        expect(result.markdownReport).toContain("# Multi-Framework Compliance Report");
        expect(result.combinedScore).toBeGreaterThanOrEqual(0);
        expect(result.combinedScore).toBeLessThanOrEqual(100);
        expect(result.status).toMatch(/compliant|at_risk|non_compliant/);
    });
    it("should handle single framework in multi-assessment", async () => {
        const result = await runComplianceAssessment({
            projectPath: "/test/project",
            findings: mockFindings,
            frameworks: ["PCI-DSS"],
            collectEvidence: false,
            verifyAuditTrail: false,
        });
        // When single framework, should still work correctly
        expect(result.reports["PCI-DSS"]).toBeDefined();
        expect(result.combinedScore).toBe(result.reports["PCI-DSS"]?.status.complianceScore);
    });
    it("should generate compliance summary", async () => {
        const result = await runComplianceAssessment({
            projectPath: "/test/project",
            findings: mockFindings,
            frameworks: ["SOC2", "HIPAA"],
            collectEvidence: false,
            verifyAuditTrail: false,
        });
        const summary = generateComplianceSummary(result);
        expect(summary).toContain("Compliance:");
        expect(summary).toContain("Frameworks: SOC2, HIPAA");
        expect(summary).toContain("Combined Score:");
        expect(summary).toContain("SOC2:");
        expect(summary).toContain("HIPAA:");
    });
    it("should determine status based on findings severity", async () => {
        const criticalFindings = [
            {
                id: "crit-001",
                severity: "critical",
                category: "security",
                description: "Critical vulnerability",
                confidence: 100,
                evidence: "Test",
                verifications: [],
                created_at: new Date().toISOString(),
            },
        ];
        const result = await runSingleFrameworkAssessment({
            projectPath: "/test/project",
            findings: criticalFindings,
            framework: "GDPR",
            collectEvidence: false,
            verifyAuditTrail: false,
        });
        // Critical findings should result in at_risk or non_compliant status
        expect(["at_risk", "non_compliant"]).toContain(result.status);
    });
    it("should be compliant with no findings", async () => {
        const result = await runSingleFrameworkAssessment({
            projectPath: "/test/project",
            findings: [],
            framework: "CIS",
            collectEvidence: false,
            verifyAuditTrail: false,
        });
        expect(result.status).toBe("compliant");
        expect(result.report.status.complianceScore).toBe(100);
    });
});
describe("All Frameworks Support", () => {
    const mockFindings = createMockFindings();
    const allFrameworks = [
        "SOC2",
        "ISO27001",
        "PCI-DSS",
        "HIPAA",
        "42-CFR-PART-2",
        "GDPR",
        "NIST-800-53",
        "CIS",
        "OWASP-LLM",
        "NIST-AI-RMF",
        "MITRE-ATLAS",
        "EU-AI-ACT",
        "ISO-42001",
    ];
    it.each(allFrameworks)("should generate report for %s framework", async (framework) => {
        const result = await runSingleFrameworkAssessment({
            projectPath: "/test/project",
            findings: mockFindings,
            framework,
            collectEvidence: false,
            verifyAuditTrail: false,
            includeAttestation: true,
        });
        expect(result.report).toBeDefined();
        expect(result.report.framework).toBe(framework);
        expect(result.markdownReport).toContain(`# ${framework} Compliance Report`);
        expect(result.markdownReport).toContain("## Attestation");
    });
    it("should generate attestation for all frameworks", () => {
        for (const framework of allFrameworks) {
            const attestation = getFrameworkAttestation(framework);
            expect(attestation).toBeDefined();
            expect(attestation.fullName.length).toBeGreaterThan(0);
        }
    });
});
//# sourceMappingURL=compliance-bundle.test.js.map