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

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

  user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
  course_id UUID NOT NULL REFERENCES education.courses(id) ON DELETE CASCADE,
  enrollment_id UUID NOT NULL REFERENCES education.enrollments(id) ON DELETE CASCADE,

  -- Review
  rating INTEGER NOT NULL CHECK (rating >= 1 AND rating <= 5),
  title VARCHAR(200),
  content TEXT,

  -- Moderación
  is_approved BOOLEAN DEFAULT false,
  is_featured BOOLEAN DEFAULT false,
  approved_by UUID REFERENCES auth.users(id),
  approved_at TIMESTAMPTZ,

  -- Votos útiles
  helpful_votes INTEGER DEFAULT 0,

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

  CONSTRAINT unique_user_course_review UNIQUE(user_id, course_id)
);

-- Índices
CREATE INDEX idx_reviews_course ON education.course_reviews(course_id);
CREATE INDEX idx_reviews_user ON education.course_reviews(user_id);
CREATE INDEX idx_reviews_rating ON education.course_reviews(rating);
CREATE INDEX idx_reviews_approved ON education.course_reviews(is_approved) WHERE is_approved = true;
CREATE INDEX idx_reviews_featured ON education.course_reviews(is_featured) WHERE is_featured = true;
CREATE INDEX idx_reviews_helpful ON education.course_reviews(helpful_votes DESC);

-- Comentarios
COMMENT ON TABLE education.course_reviews IS 'Reviews y calificaciones de cursos por usuarios';
COMMENT ON COLUMN education.course_reviews.is_approved IS 'Review aprobada por moderador';
COMMENT ON COLUMN education.course_reviews.is_featured IS 'Review destacada para mostrar en página del curso';
COMMENT ON COLUMN education.course_reviews.helpful_votes IS 'Número de votos útiles de otros usuarios';
