-- Migration 038: Referenzwert-Typen — Kategorie, Datentyp, Plausibilisierung; confidence als Diskretwert
-- Date: 2026-04-06

ALTER TABLE reference_value_types ADD COLUMN IF NOT EXISTS category TEXT;

ALTER TABLE reference_value_types ADD COLUMN IF NOT EXISTS value_data_type VARCHAR(32) NOT NULL DEFAULT 'decimal';

ALTER TABLE reference_value_types ADD COLUMN IF NOT EXISTS validation_rules JSONB NOT NULL DEFAULT '{}';

ALTER TABLE reference_value_types DROP CONSTRAINT IF EXISTS rvt_value_data_type_chk;

ALTER TABLE reference_value_types ADD CONSTRAINT rvt_value_data_type_chk CHECK (
    value_data_type IN ('integer', 'decimal', 'percentage', 'text', 'enum')
);

COMMENT ON COLUMN reference_value_types.category IS 'Freitext-Kategorie (UI/Admin)';
COMMENT ON COLUMN reference_value_types.value_data_type IS 'Logischer Wert-Typ für Erfassung & Validierung';
COMMENT ON COLUMN reference_value_types.validation_rules IS 'JSON: min, max, positive_only, max_length, not_empty, allowed_values[]';

-- Bestehende Seeds mit sinnvollen Defaults
UPDATE reference_value_types SET
    value_data_type = 'integer',
    validation_rules = '{"min": 40, "max": 240, "positive_only": true}'::jsonb
WHERE key IN ('max_heart_rate', 'resting_heart_rate');

UPDATE reference_value_types SET
    value_data_type = 'integer',
    validation_rules = '{"min": 80, "max": 210, "positive_only": true}'::jsonb
WHERE key IN ('anaerobic_threshold_hr', 'aerobic_threshold_hr');

UPDATE reference_value_types SET
    value_data_type = 'integer',
    validation_rules = '{"min": 0, "max": 21, "positive_only": false}'::jsonb
WHERE key = 'training_frequency_weekly';

UPDATE reference_value_types SET
    value_data_type = 'text',
    validation_rules = '{"max_length": 200, "not_empty": true}'::jsonb
WHERE key = 'fitness_level';

-- profile_reference_values.confidence: von NUMERIC auf diskrete Stufen
ALTER TABLE profile_reference_values ALTER COLUMN confidence DROP DEFAULT;

ALTER TABLE profile_reference_values
    ALTER COLUMN confidence TYPE VARCHAR(32)
    USING (NULL::varchar(32));

COMMENT ON COLUMN profile_reference_values.confidence IS 'high | medium | low | unknown';

-- Optionaler leerer Text (not_empty=false): leere Zeichenkette statt „kein Wert“
ALTER TABLE profile_reference_values DROP CONSTRAINT IF EXISTS profile_reference_values_value_ck;
ALTER TABLE profile_reference_values ADD CONSTRAINT profile_reference_values_value_ck CHECK (
    value_numeric IS NOT NULL OR value_text IS NOT NULL
);
