-- Evidence Checks: Automated compliance verification
-- Migration 053

CREATE TABLE compliance_evidence_checks (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    project_id UUID,
    check_code VARCHAR(50) NOT NULL,
    title VARCHAR(500) NOT NULL,
    description TEXT,
    check_type VARCHAR(30) NOT NULL
        CHECK (check_type IN ('tls_scan','header_check','certificate_check',
               'config_scan','api_scan','dns_check','port_scan')),
    target_url TEXT,
    target_config JSONB DEFAULT '{}',
    linked_control_ids JSONB DEFAULT '[]',
    frequency VARCHAR(20) DEFAULT 'monthly'
        CHECK (frequency IN ('daily','weekly','monthly','quarterly','manual')),
    last_run_at TIMESTAMPTZ,
    next_run_at TIMESTAMPTZ,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (tenant_id, project_id, check_code)
);

CREATE TABLE compliance_evidence_check_results (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    check_id UUID NOT NULL REFERENCES compliance_evidence_checks(id) ON DELETE CASCADE,
    tenant_id UUID NOT NULL,
    run_status VARCHAR(20) NOT NULL DEFAULT 'running'
        CHECK (run_status IN ('running','passed','failed','warning','error')),
    result_data JSONB NOT NULL DEFAULT '{}',
    summary TEXT,
    findings_count INTEGER DEFAULT 0,
    critical_findings INTEGER DEFAULT 0,
    evidence_id UUID,
    duration_ms INTEGER,
    run_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE compliance_evidence_control_map (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    evidence_id UUID NOT NULL,
    control_code VARCHAR(50) NOT NULL,
    mapping_type VARCHAR(20) DEFAULT 'supports'
        CHECK (mapping_type IN ('supports','partially_supports','required')),
    verified_at TIMESTAMPTZ,
    verified_by VARCHAR(255),
    notes TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (tenant_id, evidence_id, control_code)
);

CREATE INDEX idx_evidence_checks_tenant ON compliance_evidence_checks(tenant_id);
CREATE INDEX idx_evidence_checks_type ON compliance_evidence_checks(check_type);
CREATE INDEX idx_evidence_checks_active ON compliance_evidence_checks(is_active);
CREATE INDEX idx_check_results_check ON compliance_evidence_check_results(check_id);
CREATE INDEX idx_check_results_status ON compliance_evidence_check_results(run_status);
CREATE INDEX idx_evidence_control_map_tenant ON compliance_evidence_control_map(tenant_id);
CREATE INDEX idx_evidence_control_map_control ON compliance_evidence_control_map(control_code);
