-- Migration 023: AI System Registration Schema (Art. 49 AI Act)
-- Tracks EU AI Database registrations for High-Risk AI systems

CREATE TABLE IF NOT EXISTS ai_system_registrations (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,

    -- System identification
    system_name VARCHAR(500) NOT NULL,
    system_version VARCHAR(100),
    system_description TEXT,
    intended_purpose TEXT,

    -- Provider info
    provider_name VARCHAR(500),
    provider_legal_form VARCHAR(200),
    provider_address TEXT,
    provider_country VARCHAR(10),
    eu_representative_name VARCHAR(500),
    eu_representative_contact TEXT,

    -- Classification
    risk_classification VARCHAR(50) DEFAULT 'not_classified',
    -- CHECK (risk_classification IN ('not_classified', 'minimal_risk', 'limited_risk', 'high_risk', 'unacceptable'))
    annex_iii_category VARCHAR(200),
    gpai_classification VARCHAR(50) DEFAULT 'none',
    -- CHECK (gpai_classification IN ('none', 'standard', 'systemic'))

    -- Conformity
    conformity_assessment_type VARCHAR(50),
    -- CHECK (conformity_assessment_type IN ('internal', 'third_party', 'not_required'))
    notified_body_name VARCHAR(500),
    notified_body_id VARCHAR(100),
    ce_marking BOOLEAN DEFAULT false,

    -- Training data
    training_data_categories JSONB DEFAULT '[]'::jsonb,
    training_data_summary TEXT,

    -- Registration status
    registration_status VARCHAR(50) DEFAULT 'draft',
    -- CHECK (registration_status IN ('draft', 'ready', 'submitted', 'registered', 'update_required', 'withdrawn'))
    eu_database_id VARCHAR(200),
    registration_date TIMESTAMPTZ,
    last_update_date TIMESTAMPTZ,

    -- Links to other assessments
    ucca_assessment_id UUID,
    decision_tree_result_id UUID,

    -- Export data (cached JSON for EU submission)
    export_data JSONB,

    -- Audit
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    created_by VARCHAR(200),
    submitted_by VARCHAR(200)
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_air_tenant ON ai_system_registrations (tenant_id);
CREATE INDEX IF NOT EXISTS idx_air_status ON ai_system_registrations (registration_status);
CREATE INDEX IF NOT EXISTS idx_air_classification ON ai_system_registrations (risk_classification);
CREATE INDEX IF NOT EXISTS idx_air_ucca ON ai_system_registrations (ucca_assessment_id);
