-- =============================================================================
-- Migration 004: System Screening Tables
--
-- Tables for SBOM generation and vulnerability scanning results.
-- =============================================================================

CREATE TABLE IF NOT EXISTS compliance_screenings (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id VARCHAR(255) NOT NULL,
    status VARCHAR(20) DEFAULT 'pending',
    sbom_format VARCHAR(50) DEFAULT 'CycloneDX',
    sbom_version VARCHAR(20) DEFAULT '1.5',
    total_components INTEGER DEFAULT 0,
    total_issues INTEGER DEFAULT 0,
    critical_issues INTEGER DEFAULT 0,
    high_issues INTEGER DEFAULT 0,
    medium_issues INTEGER DEFAULT 0,
    low_issues INTEGER DEFAULT 0,
    sbom_data JSONB,
    started_at TIMESTAMPTZ,
    completed_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_screenings_tenant ON compliance_screenings(tenant_id);
CREATE INDEX IF NOT EXISTS idx_screenings_status ON compliance_screenings(status);

CREATE TABLE IF NOT EXISTS compliance_security_issues (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    screening_id UUID NOT NULL REFERENCES compliance_screenings(id) ON DELETE CASCADE,
    severity VARCHAR(20) NOT NULL,
    title VARCHAR(500) NOT NULL,
    description TEXT,
    cve VARCHAR(50),
    cvss FLOAT,
    affected_component VARCHAR(255),
    affected_version VARCHAR(100),
    fixed_in VARCHAR(100),
    remediation TEXT,
    status VARCHAR(20) DEFAULT 'OPEN',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_security_issues_screening ON compliance_security_issues(screening_id);
CREATE INDEX IF NOT EXISTS idx_security_issues_severity ON compliance_security_issues(severity);
