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

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

  -- Relación (puede estar asociado a módulo o lección)
  module_id UUID REFERENCES education.modules(id) ON DELETE CASCADE,
  lesson_id UUID REFERENCES education.lessons(id) ON DELETE CASCADE,

  -- Información básica
  title VARCHAR(200) NOT NULL,
  description TEXT,

  -- Configuración
  passing_score_percentage INTEGER DEFAULT 70, -- % mínimo para aprobar
  max_attempts INTEGER, -- NULL = intentos ilimitados
  time_limit_minutes INTEGER, -- NULL = sin límite de tiempo

  -- Opciones
  shuffle_questions BOOLEAN DEFAULT true,
  shuffle_answers BOOLEAN DEFAULT true,
  show_correct_answers BOOLEAN DEFAULT true, -- Después de completar

  -- Gamificación
  xp_reward INTEGER DEFAULT 50,
  xp_perfect_score_bonus INTEGER DEFAULT 20,

  -- Estado
  is_active BOOLEAN DEFAULT true,

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

  CONSTRAINT valid_passing_score CHECK (passing_score_percentage > 0 AND passing_score_percentage <= 100),
  CONSTRAINT quiz_association CHECK (
    (module_id IS NOT NULL AND lesson_id IS NULL) OR
    (module_id IS NULL AND lesson_id IS NOT NULL)
  )
);

-- Índices
CREATE INDEX idx_quizzes_module ON education.quizzes(module_id);
CREATE INDEX idx_quizzes_lesson ON education.quizzes(lesson_id);
CREATE INDEX idx_quizzes_active ON education.quizzes(is_active) WHERE is_active = true;

-- Comentarios
COMMENT ON TABLE education.quizzes IS 'Quizzes/evaluaciones asociadas a módulos o lecciones';
COMMENT ON COLUMN education.quizzes.max_attempts IS 'NULL = intentos ilimitados';
COMMENT ON COLUMN education.quizzes.time_limit_minutes IS 'NULL = sin límite de tiempo';
COMMENT ON COLUMN education.quizzes.xp_perfect_score_bonus IS 'XP bonus por obtener 100% de score';
