-- Migration 024: Goal Type Registry (Flexible Goal System)
-- Date: 2026-03-27
-- Purpose: Enable dynamic goal types without code changes

-- ============================================================================
-- Goal Type Definitions
-- ============================================================================

CREATE TABLE IF NOT EXISTS goal_type_definitions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    -- Unique identifier (used in code)
    type_key VARCHAR(50) UNIQUE NOT NULL,

    -- Display metadata
    label_de VARCHAR(100) NOT NULL,
    label_en VARCHAR(100),
    unit VARCHAR(20) NOT NULL,
    icon VARCHAR(10),
    category VARCHAR(50),  -- body, mind, activity, nutrition, recovery, custom

    -- Data source configuration
    source_table VARCHAR(50),       -- Which table to query
    source_column VARCHAR(50),      -- Which column to fetch
    aggregation_method VARCHAR(20), -- How to aggregate: latest, avg_7d, avg_30d, sum_30d, count_7d, count_30d, min_30d, max_30d

    -- Complex calculations (optional)
    -- For types like lean_mass that need custom logic
    -- JSON format: {"type": "formula", "dependencies": ["weight", "body_fat"], "expression": "..."}
    calculation_formula TEXT,

    -- Metadata
    description TEXT,
    is_active BOOLEAN DEFAULT true,
    is_system BOOLEAN DEFAULT false,  -- System types cannot be deleted

    -- Audit
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_goal_type_definitions_active ON goal_type_definitions(is_active) WHERE is_active = true;
CREATE INDEX IF NOT EXISTS idx_goal_type_definitions_category ON goal_type_definitions(category);

COMMENT ON TABLE goal_type_definitions IS 'Registry of available goal types - allows dynamic goal creation without code changes';
COMMENT ON COLUMN goal_type_definitions.type_key IS 'Unique key used in code (e.g., weight, meditation_minutes)';
COMMENT ON COLUMN goal_type_definitions.aggregation_method IS 'latest = most recent value, avg_7d = 7-day average, count_7d = count in last 7 days, etc.';
COMMENT ON COLUMN goal_type_definitions.calculation_formula IS 'JSON for complex calculations like lean_mass = weight - (weight * bf_pct / 100)';
COMMENT ON COLUMN goal_type_definitions.is_system IS 'System types are protected from deletion (core functionality)';

-- ============================================================================
-- Seed Data: Migrate existing 8 goal types
-- ============================================================================

-- 1. Weight (simple - latest value)
INSERT INTO goal_type_definitions (
    type_key, label_de, label_en, unit, icon, category,
    source_table, source_column, aggregation_method,
    description, is_system
) VALUES (
    'weight', 'Gewicht', 'Weight', 'kg', '⚖️', 'body',
    'weight_log', 'weight', 'latest',
    'Aktuelles Körpergewicht', true
)
ON CONFLICT (type_key) DO NOTHING;

-- 2. Body Fat (simple - latest value)
INSERT INTO goal_type_definitions (
    type_key, label_de, label_en, unit, icon, category,
    source_table, source_column, aggregation_method,
    description, is_system
) VALUES (
    'body_fat', 'Körperfett', 'Body Fat', '%', '📊', 'body',
    'caliper_log', 'body_fat_pct', 'latest',
    'Körperfettanteil aus Caliper-Messung', true
)
ON CONFLICT (type_key) DO NOTHING;

-- 3. Lean Mass (complex - calculation formula)
INSERT INTO goal_type_definitions (
    type_key, label_de, label_en, unit, icon, category,
    calculation_formula,
    description, is_system
) VALUES (
    'lean_mass', 'Muskelmasse', 'Lean Mass', 'kg', '💪', 'body',
    '{"type": "lean_mass", "dependencies": ["weight_log.weight", "caliper_log.body_fat_pct"], "formula": "weight - (weight * body_fat_pct / 100)"}',
    'Fettfreie Körpermasse (berechnet aus Gewicht und Körperfett)', true
)
ON CONFLICT (type_key) DO NOTHING;

-- 4. VO2 Max (simple - latest value)
INSERT INTO goal_type_definitions (
    type_key, label_de, label_en, unit, icon, category,
    source_table, source_column, aggregation_method,
    description, is_system
) VALUES (
    'vo2max', 'VO2Max', 'VO2Max', 'ml/kg/min', '🫁', 'recovery',
    'vitals_baseline', 'vo2_max', 'latest',
    'Maximale Sauerstoffaufnahme (geschätzt oder gemessen)', true
)
ON CONFLICT (type_key) DO NOTHING;

-- 5. Resting Heart Rate (simple - latest value)
INSERT INTO goal_type_definitions (
    type_key, label_de, label_en, unit, icon, category,
    source_table, source_column, aggregation_method,
    description, is_system
) VALUES (
    'rhr', 'Ruhepuls', 'Resting Heart Rate', 'bpm', '💓', 'recovery',
    'vitals_baseline', 'resting_hr', 'latest',
    'Ruhepuls morgens vor dem Aufstehen', true
)
ON CONFLICT (type_key) DO NOTHING;

-- 6. Blood Pressure (placeholder - compound goal for v2.0)
-- Currently limited to single value, v2.0 will support systolic/diastolic
INSERT INTO goal_type_definitions (
    type_key, label_de, label_en, unit, icon, category,
    source_table, source_column, aggregation_method,
    description, is_system
) VALUES (
    'bp', 'Blutdruck', 'Blood Pressure', 'mmHg', '❤️', 'recovery',
    'blood_pressure_log', 'systolic', 'latest',
    'Blutdruck (aktuell nur systolisch, v2.0: beide Werte)', true
)
ON CONFLICT (type_key) DO NOTHING;

-- 7. Strength (placeholder - no data source yet)
INSERT INTO goal_type_definitions (
    type_key, label_de, label_en, unit, icon, category,
    description, is_system, is_active
) VALUES (
    'strength', 'Kraft', 'Strength', 'kg', '🏋️', 'activity',
    'Maximalkraft (Platzhalter, Datenquelle in v2.0)', true, false
)
ON CONFLICT (type_key) DO NOTHING;

-- 8. Flexibility (placeholder - no data source yet)
INSERT INTO goal_type_definitions (
    type_key, label_de, label_en, unit, icon, category,
    description, is_system, is_active
) VALUES (
    'flexibility', 'Beweglichkeit', 'Flexibility', 'cm', '🤸', 'activity',
    'Beweglichkeit (Platzhalter, Datenquelle in v2.0)', true, false
)
ON CONFLICT (type_key) DO NOTHING;

-- ============================================================================
-- Example: Future custom goal types (commented out, for reference)
-- ============================================================================

/*
-- Meditation Minutes (avg last 7 days)
INSERT INTO goal_type_definitions (
    type_key, label_de, unit, icon, category,
    source_table, source_column, aggregation_method,
    description, is_system
) VALUES (
    'meditation_minutes', 'Meditation', 'min/Tag', '🧘', 'mind',
    'meditation_log', 'duration_minutes', 'avg_7d',
    'Durchschnittliche Meditationsdauer pro Tag (7 Tage)', false
);

-- Training Frequency (count last 7 days)
INSERT INTO goal_type_definitions (
    type_key, label_de, unit, icon, category,
    source_table, source_column, aggregation_method,
    description, is_system
) VALUES (
    'training_frequency', 'Trainingshäufigkeit', 'x/Woche', '📅', 'activity',
    'activity_log', 'id', 'count_7d',
    'Anzahl Trainingseinheiten pro Woche', false
);

-- Sleep Quality (avg last 7 days)
INSERT INTO goal_type_definitions (
    type_key, label_de, unit, icon, category,
    source_table, source_column, aggregation_method,
    description, is_system
) VALUES (
    'sleep_quality', 'Schlafqualität', '%', '💤', 'recovery',
    'sleep_log', 'quality_score', 'avg_7d',
    'Durchschnittliche Schlafqualität (Deep+REM Anteil)', false
);
*/
