-- Plan entraînement / séances type Garmin — MySQL 8+
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

DROP TABLE IF EXISTS schedule_entries;
DROP TABLE IF EXISTS workout_steps;
DROP TABLE IF EXISTS workouts;

SET FOREIGN_KEY_CHECKS = 1;

CREATE TABLE workouts (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  title VARCHAR(255) NOT NULL,
  notes TEXT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE workout_steps (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  workout_id INT UNSIGNED NOT NULL,
  parent_id INT UNSIGNED NULL,
  step_order INT UNSIGNED NOT NULL DEFAULT 0,
  node_type ENUM('repeat','run','recovery','warmup','cooldown') NOT NULL,
  repeat_times INT UNSIGNED NULL COMMENT 'Renseigné seulement si node_type = repeat',
  duration_kind ENUM('time','distance') NULL,
  duration_seconds INT UNSIGNED NULL,
  duration_meters INT UNSIGNED NULL,
  target_kind ENUM('none','speed_kmh','pace_sec_per_km','hr_zone','hr_bpm') NOT NULL DEFAULT 'none',
  target_low DECIMAL(8,2) NULL,
  target_high DECIMAL(8,2) NULL,
  target_label VARCHAR(64) NULL COMMENT 'ex. zone affichée ou libellé libre',
  CONSTRAINT fk_ws_workout FOREIGN KEY (workout_id) REFERENCES workouts(id) ON DELETE CASCADE,
  CONSTRAINT fk_ws_parent FOREIGN KEY (parent_id) REFERENCES workout_steps(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE INDEX idx_ws_workout ON workout_steps(workout_id);
CREATE INDEX idx_ws_parent_order ON workout_steps(parent_id, step_order);

CREATE TABLE schedule_entries (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  entry_date DATE NOT NULL,
  session_type ENUM('rest','easy','workout','race','other') NOT NULL DEFAULT 'other',
  title VARCHAR(255) NULL,
  description TEXT NULL,
  workout_id INT UNSIGNED NULL,
  CONSTRAINT fk_se_workout FOREIGN KEY (workout_id) REFERENCES workouts(id) ON DELETE SET NULL,
  UNIQUE KEY uq_schedule_date (entry_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
