-- 06-01: Add swapped_from_id to workout_logs for tracking workout swaps
ALTER TABLE workout_logs 
ADD COLUMN IF NOT EXISTS swapped_from_id INTEGER REFERENCES workout_logs(id) ON DELETE SET NULL,
ADD COLUMN IF NOT EXISTS source_type VARCHAR(50) DEFAULT 'program', -- 'program' or 'custom'
ADD COLUMN IF NOT EXISTS custom_workout_id INTEGER,
ADD COLUMN IF NOT EXISTS custom_workout_exercise_id INTEGER;

-- Create workout_swaps table for swap history
CREATE TABLE IF NOT EXISTS workout_swaps (
  id SERIAL PRIMARY KEY,
  user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  original_log_id INTEGER REFERENCES workout_logs(id) ON DELETE CASCADE,
  swapped_log_id INTEGER REFERENCES workout_logs(id) ON DELETE CASCADE,
  swap_date DATE NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_workout_swaps_user_date ON workout_swaps(user_id, swap_date);
CREATE INDEX IF NOT EXISTS idx_workout_swaps_original_log ON workout_swaps(original_log_id);

-- 06-02: Create muscle_group_recovery table for tracking recovery per muscle group
CREATE TABLE IF NOT EXISTS muscle_group_recovery (
  id SERIAL PRIMARY KEY,
  user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  muscle_group VARCHAR(100) NOT NULL,
  last_workout_date TIMESTAMP,
  intensity NUMERIC(3,2) DEFAULT 0.5,
  exercises_count INTEGER DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE(user_id, muscle_group)
);

CREATE INDEX IF NOT EXISTS idx_muscle_group_recovery_user ON muscle_group_recovery(user_id);
CREATE INDEX IF NOT EXISTS idx_muscle_group_recovery_last_workout ON muscle_group_recovery(user_id, last_workout_date);

-- 06-01 Extended: Create custom_workouts table for custom workout support
CREATE TABLE IF NOT EXISTS custom_workouts (
  id SERIAL PRIMARY KEY,
  user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  name VARCHAR(255) NOT NULL,
  description TEXT,
  source_program_day_id INTEGER REFERENCES program_days(id),
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_custom_workouts_user ON custom_workouts(user_id);

-- Create custom_workout_exercises table
CREATE TABLE IF NOT EXISTS custom_workout_exercises (
  id SERIAL PRIMARY KEY,
  custom_workout_id INTEGER NOT NULL REFERENCES custom_workouts(id) ON DELETE CASCADE,
  exercise_id INTEGER NOT NULL REFERENCES exercises(id),
  sets INTEGER DEFAULT 3,
  reps_min INTEGER DEFAULT 8,
  reps_max INTEGER DEFAULT 12,
  order_index INTEGER,
  replaced_exercise_id INTEGER REFERENCES exercises(id),
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_custom_workout_exercises_workout ON custom_workout_exercises(custom_workout_id);
