-- Migration 056: kcal_per_km Trigger — manuelles Leeren bei UPDATE erlauben
-- Problem: calculate_avg_hr_percent (014) setzte bei jedem UPDATE kcal_per_km aus
-- kcal_active/distance_km, sobald beide gesetzt waren — ein bewusst geleertes Feld
-- erschien sofort wieder.
-- Lösung: automatische Ableitung nur noch bei INSERT (wenn kcal_per_km noch NULL ist).

CREATE OR REPLACE FUNCTION calculate_avg_hr_percent()
RETURNS TRIGGER AS $$
DECLARE
    user_max_hr INTEGER;
BEGIN
    SELECT hf_max INTO user_max_hr
    FROM profiles
    WHERE id = NEW.profile_id;

    IF NEW.hr_avg IS NOT NULL AND user_max_hr IS NOT NULL AND user_max_hr > 0 THEN
        NEW.avg_hr_percent := (NEW.hr_avg::float / user_max_hr::float) * 100;
    END IF;

    IF TG_OP = 'INSERT' THEN
        IF NEW.kcal_active IS NOT NULL AND NEW.distance_km IS NOT NULL AND NEW.distance_km > 0 THEN
            IF NEW.kcal_per_km IS NULL THEN
                NEW.kcal_per_km := NEW.kcal_active::float / NEW.distance_km;
            END IF;
        END IF;
    END IF;

    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DO $$
BEGIN
    RAISE NOTICE '✓ Migration 056: kcal_per_km nur noch bei INSERT auto-abgeleitet';
END $$;
