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

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

  -- Relaciones
  user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
  quiz_id UUID NOT NULL REFERENCES education.quizzes(id) ON DELETE RESTRICT,
  enrollment_id UUID REFERENCES education.enrollments(id) ON DELETE SET NULL,

  -- Estado del intento
  is_completed BOOLEAN DEFAULT false,
  is_passed BOOLEAN DEFAULT false,

  -- Respuestas del usuario
  user_answers JSONB, -- [{questionId, answer, isCorrect, points}]

  -- Puntuación
  score_points INTEGER DEFAULT 0,
  max_points INTEGER DEFAULT 0,
  score_percentage DECIMAL(5,2) DEFAULT 0.00,

  -- Tiempo
  started_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  completed_at TIMESTAMPTZ,
  time_taken_seconds INTEGER,

  -- XP ganado
  xp_earned INTEGER DEFAULT 0,

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

  CONSTRAINT valid_score_percentage CHECK (score_percentage >= 0 AND score_percentage <= 100)
);

-- Índices
CREATE INDEX idx_quiz_attempts_user ON education.quiz_attempts(user_id);
CREATE INDEX idx_quiz_attempts_quiz ON education.quiz_attempts(quiz_id);
CREATE INDEX idx_quiz_attempts_enrollment ON education.quiz_attempts(enrollment_id);
CREATE INDEX idx_quiz_attempts_user_quiz ON education.quiz_attempts(user_id, quiz_id);
CREATE INDEX idx_quiz_attempts_completed ON education.quiz_attempts(is_completed, completed_at);

-- Comentarios
COMMENT ON TABLE education.quiz_attempts IS 'Intentos de los usuarios en los quizzes';
COMMENT ON COLUMN education.quiz_attempts.user_answers IS 'Respuestas del usuario: [{questionId, answer, isCorrect, points}]';
COMMENT ON COLUMN education.quiz_attempts.time_taken_seconds IS 'Tiempo total empleado en segundos';
