-- Migration 020: IACE Component Library, Energy Sources & Pattern Engine
-- Adds machine component library (120 entries), energy sources (20 entries),
-- and extends existing iace_components with library references and tags.

-- ============================================================================
-- Component Library (120 entries, C001-C120)
-- ============================================================================
CREATE TABLE IF NOT EXISTS iace_component_library (
    id TEXT PRIMARY KEY,
    name_de TEXT NOT NULL,
    name_en TEXT NOT NULL,
    category TEXT NOT NULL,
    description_de TEXT DEFAULT '',
    typical_hazard_categories JSONB DEFAULT '[]',
    typical_energy_sources JSONB DEFAULT '[]',
    maps_to_component_type TEXT NOT NULL,
    tags JSONB DEFAULT '[]',
    sort_order INT DEFAULT 0
);

-- ============================================================================
-- Energy Sources (20 entries, EN01-EN20)
-- ============================================================================
CREATE TABLE IF NOT EXISTS iace_energy_sources (
    id TEXT PRIMARY KEY,
    name_de TEXT NOT NULL,
    name_en TEXT NOT NULL,
    description_de TEXT DEFAULT '',
    typical_components JSONB DEFAULT '[]',
    typical_hazard_categories JSONB DEFAULT '[]',
    tags JSONB DEFAULT '[]',
    sort_order INT DEFAULT 0
);

-- ============================================================================
-- Extend existing iace_components with library references
-- ============================================================================
ALTER TABLE iace_components ADD COLUMN IF NOT EXISTS library_component_id TEXT;
ALTER TABLE iace_components ADD COLUMN IF NOT EXISTS energy_source_ids JSONB DEFAULT '[]';
ALTER TABLE iace_components ADD COLUMN IF NOT EXISTS tags JSONB DEFAULT '[]';

-- ============================================================================
-- Pattern matching results table (audit trail for applied patterns)
-- ============================================================================
CREATE TABLE IF NOT EXISTS iace_pattern_results (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    project_id UUID NOT NULL REFERENCES iace_projects(id) ON DELETE CASCADE,
    matched_patterns JSONB DEFAULT '[]',
    resolved_tags JSONB DEFAULT '[]',
    input_data JSONB DEFAULT '{}',
    created_at TIMESTAMPTZ DEFAULT NOW(),
    created_by TEXT DEFAULT ''
);

CREATE INDEX IF NOT EXISTS idx_iace_pattern_results_project ON iace_pattern_results(project_id);
CREATE INDEX IF NOT EXISTS idx_iace_component_library_category ON iace_component_library(category);
