-- ============================================
-- PastPaper Master — Shared course library fields
-- Version: 002
-- Date: 2026-03-24
-- ============================================

-- Shared library / canonical import metadata on papers
ALTER TABLE papers
  ADD COLUMN IF NOT EXISTS source_kind TEXT NOT NULL DEFAULT 'user_upload'
    CHECK (source_kind IN ('user_upload', 'course_library')),
  ADD COLUMN IF NOT EXISTS source_exam_key TEXT,
  ADD COLUMN IF NOT EXISTS part_label TEXT
    CHECK (part_label IN ('A', 'B')),
  ADD COLUMN IF NOT EXISTS source_question_filename TEXT,
  ADD COLUMN IF NOT EXISTS source_answer_filename TEXT;

CREATE UNIQUE INDEX IF NOT EXISTS idx_papers_course_library_exam_key
  ON papers(source_exam_key)
  WHERE source_kind = 'course_library' AND source_exam_key IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_papers_course_lookup
  ON papers(course_code, year, term, exam_type, part_label);

-- Grading results should persist awarded score
ALTER TABLE user_attempts
  ADD COLUMN IF NOT EXISTS score_given INTEGER;

CREATE INDEX IF NOT EXISTS idx_attempts_errorbook_active
  ON user_attempts(user_id, created_at DESC)
  WHERE in_error_book = true AND mastered = false;

-- The backend and frontend already support true_false; schema must match.
ALTER TABLE paper_questions
  DROP CONSTRAINT IF EXISTS paper_questions_question_type_check;

ALTER TABLE paper_questions
  ADD CONSTRAINT paper_questions_question_type_check
  CHECK (question_type IN ('mc', 'true_false', 'fill_blank', 'long_question'));
