-- =====================================================
-- TABLE: education.user_gamification_profile
-- =====================================================
-- Proyecto: OrbiQuant IA (Trading Platform)
-- Módulo: OQI-002 - Education
-- Especificación: Tabla adicional para gamificación
-- =====================================================

CREATE TABLE education.user_gamification_profile (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,

  -- XP y nivel
  total_xp INTEGER NOT NULL DEFAULT 0,
  current_level INTEGER NOT NULL DEFAULT 1,
  xp_to_next_level INTEGER NOT NULL DEFAULT 100,

  -- Streaks
  current_streak_days INTEGER DEFAULT 0,
  longest_streak_days INTEGER DEFAULT 0,
  last_activity_date DATE,

  -- Estadísticas
  total_courses_completed INTEGER DEFAULT 0,
  total_lessons_completed INTEGER DEFAULT 0,
  total_quizzes_passed INTEGER DEFAULT 0,
  total_certificates_earned INTEGER DEFAULT 0,
  average_quiz_score DECIMAL(5,2) DEFAULT 0.00,

  -- Ranking
  weekly_xp INTEGER DEFAULT 0,
  monthly_xp INTEGER DEFAULT 0,

  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

  CONSTRAINT unique_user_gamification UNIQUE(user_id),
  CONSTRAINT valid_level CHECK (current_level >= 1),
  CONSTRAINT valid_xp CHECK (total_xp >= 0),
  CONSTRAINT valid_streak CHECK (current_streak_days >= 0 AND longest_streak_days >= 0),
  CONSTRAINT valid_avg_score CHECK (average_quiz_score >= 0 AND average_quiz_score <= 100)
);

-- Índices
CREATE INDEX idx_gamification_user ON education.user_gamification_profile(user_id);
CREATE INDEX idx_gamification_level ON education.user_gamification_profile(current_level DESC);
CREATE INDEX idx_gamification_xp ON education.user_gamification_profile(total_xp DESC);
CREATE INDEX idx_gamification_weekly ON education.user_gamification_profile(weekly_xp DESC);
CREATE INDEX idx_gamification_monthly ON education.user_gamification_profile(monthly_xp DESC);

-- Comentarios
COMMENT ON TABLE education.user_gamification_profile IS 'Perfil de gamificación del usuario con XP, niveles, streaks y estadísticas';
COMMENT ON COLUMN education.user_gamification_profile.current_streak_days IS 'Días consecutivos de actividad actual';
COMMENT ON COLUMN education.user_gamification_profile.longest_streak_days IS 'Racha más larga de días consecutivos';
COMMENT ON COLUMN education.user_gamification_profile.weekly_xp IS 'XP acumulado en la semana actual (para leaderboards)';
COMMENT ON COLUMN education.user_gamification_profile.monthly_xp IS 'XP acumulado en el mes actual (para leaderboards)';
