-- Track which exercises were swapped
CREATE TABLE IF NOT EXISTS workout_swaps (
    id SERIAL PRIMARY KEY,
    user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    program_exercise_id INTEGER NOT NULL REFERENCES program_exercises(id) ON DELETE CASCADE,
    from_exercise_id INTEGER NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
    to_exercise_id INTEGER NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
    swap_date DATE NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Add reference in workout_logs to track origin
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 swap_history_id INTEGER REFERENCES workout_swaps(id) ON DELETE SET NULL;

-- Indexes for performance
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_exercise ON workout_swaps(program_exercise_id);
CREATE INDEX IF NOT EXISTS idx_workout_logs_swapped_from ON workout_logs(swapped_from_id);
CREATE INDEX IF NOT EXISTS idx_workout_logs_swap_history ON workout_logs(swap_history_id);
