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

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

  -- Relación
  quiz_id UUID NOT NULL REFERENCES education.quizzes(id) ON DELETE CASCADE,

  -- Pregunta
  question_text TEXT NOT NULL,
  question_type education.question_type NOT NULL DEFAULT 'multiple_choice',

  -- Opciones de respuesta (para multiple_choice, true_false, multiple_select)
  options JSONB, -- [{id, text, isCorrect}]

  -- Respuesta correcta (para fill_blank, code_challenge)
  correct_answer TEXT,

  -- Explicación
  explanation TEXT, -- Mostrar después de responder

  -- Recursos adicionales
  image_url VARCHAR(500),
  code_snippet TEXT,

  -- Puntuación
  points INTEGER DEFAULT 1,

  -- Ordenamiento
  display_order INTEGER DEFAULT 0,

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

  CONSTRAINT valid_options CHECK (
    (question_type NOT IN ('multiple_choice', 'true_false', 'multiple_select')) OR
    (options IS NOT NULL)
  )
);

-- Índices
CREATE INDEX idx_quiz_questions_quiz ON education.quiz_questions(quiz_id);
CREATE INDEX idx_quiz_questions_order ON education.quiz_questions(quiz_id, display_order);

-- Comentarios
COMMENT ON TABLE education.quiz_questions IS 'Preguntas individuales de los quizzes';
COMMENT ON COLUMN education.quiz_questions.options IS 'Array JSON de opciones: [{id, text, isCorrect}]';
COMMENT ON COLUMN education.quiz_questions.correct_answer IS 'Respuesta correcta para fill_blank y code_challenge';
COMMENT ON COLUMN education.quiz_questions.explanation IS 'Explicación mostrada después de responder';
