-- =====================================================
-- TABLE: education.user_achievements
-- =====================================================
-- Proyecto: OrbiQuant IA (Trading Platform)
-- Módulo: OQI-002 - Education
-- Especificación: ET-EDU-001-database.md
-- =====================================================

CREATE TABLE education.user_achievements (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

  -- Relación
  user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,

  -- Tipo de logro
  achievement_type education.achievement_type NOT NULL,

  -- Información del logro
  title VARCHAR(200) NOT NULL,
  description TEXT,
  badge_icon_url VARCHAR(500),

  -- Metadata del logro
  metadata JSONB, -- Información específica del logro

  -- Referencias
  course_id UUID REFERENCES education.courses(id) ON DELETE SET NULL,
  quiz_id UUID REFERENCES education.quizzes(id) ON DELETE SET NULL,

  -- XP bonus por el logro
  xp_bonus INTEGER DEFAULT 0,

  -- Metadata
  earned_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Índices
CREATE INDEX idx_user_achievements_user ON education.user_achievements(user_id);
CREATE INDEX idx_user_achievements_type ON education.user_achievements(achievement_type);
CREATE INDEX idx_user_achievements_earned ON education.user_achievements(earned_at DESC);
CREATE INDEX idx_user_achievements_course ON education.user_achievements(course_id);

-- Comentarios
COMMENT ON TABLE education.user_achievements IS 'Logros/badges obtenidos por los usuarios';
COMMENT ON COLUMN education.user_achievements.metadata IS 'Información adicional específica del tipo de logro';
COMMENT ON COLUMN education.user_achievements.xp_bonus IS 'XP bonus otorgado por este logro';
