-- Migration 028: Goal Categories and Priorities
-- Date: 2026-03-27
-- Purpose: Multi-dimensional goal priorities (one primary goal per category)

-- ============================================================================
-- Add category and priority columns
-- ============================================================================

ALTER TABLE goals
ADD COLUMN category VARCHAR(50),
ADD COLUMN priority INTEGER DEFAULT 2 CHECK (priority >= 1 AND priority <= 3);

COMMENT ON COLUMN goals.category IS 'Goal category: body, training, nutrition, recovery, health, other';
COMMENT ON COLUMN goals.priority IS 'Priority level: 1=high, 2=medium, 3=low';

-- ============================================================================
-- Migrate existing goals to categories based on goal_type
-- ============================================================================

UPDATE goals SET category = CASE
  -- Body composition goals
  WHEN goal_type IN ('weight', 'body_fat', 'lean_mass') THEN 'body'

  -- Training goals
  WHEN goal_type IN ('strength', 'flexibility', 'training_frequency') THEN 'training'

  -- Health/cardio goals
  WHEN goal_type IN ('vo2max', 'rhr', 'bp', 'hrv') THEN 'health'

  -- Recovery goals
  WHEN goal_type IN ('sleep_quality', 'sleep_duration', 'rest_days') THEN 'recovery'

  -- Nutrition goals
  WHEN goal_type IN ('calories', 'protein', 'healthy_eating') THEN 'nutrition'

  -- Default
  ELSE 'other'
END
WHERE category IS NULL;

-- ============================================================================
-- Set priority based on is_primary
-- ============================================================================

UPDATE goals SET priority = CASE
  WHEN is_primary = true THEN 1  -- Primary goals get priority 1
  ELSE 2                          -- Others get priority 2 (medium)
END;

-- ============================================================================
-- Create index for category-based queries
-- ============================================================================

CREATE INDEX IF NOT EXISTS idx_goals_category_priority
ON goals(profile_id, category, priority);

COMMENT ON INDEX idx_goals_category_priority IS 'Fast lookup for category-grouped goals sorted by priority';
