CREATE TABLE IF NOT EXISTS community.vocab_srs_item (
  id SERIAL PRIMARY KEY,
  user_id INTEGER NOT NULL REFERENCES community."user"(id) ON DELETE CASCADE,
  course_id INTEGER NOT NULL REFERENCES community.vocab_course(id) ON DELETE CASCADE,
  lesson_id INTEGER NULL REFERENCES community.vocab_course_lesson(id) ON DELETE SET NULL,
  item_key VARCHAR(80) NOT NULL,
  learning TEXT NOT NULL,
  reference TEXT NOT NULL,
  direction VARCHAR(8) NOT NULL DEFAULT 'BOTH',
  stage INTEGER NOT NULL DEFAULT 0,
  interval_days INTEGER NOT NULL DEFAULT 0,
  last_reviewed_at TIMESTAMP WITH TIME ZONE NULL,
  next_due_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
  correct_count INTEGER NOT NULL DEFAULT 0,
  wrong_count INTEGER NOT NULL DEFAULT 0,
  lapse_count INTEGER NOT NULL DEFAULT 0,
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
  CONSTRAINT vocab_srs_item_user_key_unique UNIQUE (user_id, item_key)
);

CREATE INDEX IF NOT EXISTS idx_vocab_srs_item_due
  ON community.vocab_srs_item (user_id, course_id, next_due_at);

CREATE INDEX IF NOT EXISTS idx_vocab_srs_item_lesson
  ON community.vocab_srs_item (user_id, course_id, lesson_id);

COMMENT ON TABLE community.vocab_srs_item IS
  'Nutzerbezogener SRS-Fortschritt pro Vokabel/Phrase aus Sprachkursen.';
COMMENT ON COLUMN community.vocab_srs_item.item_key IS
  'Stabiler deterministischer Schlüssel aus Kurs, Lektion und normalisiertem Begriffspaar.';
COMMENT ON COLUMN community.vocab_srs_item.stage IS
  'SRS-Stufe. Höhere Stufen bedeuten längere Wiederholungsintervalle.';
COMMENT ON COLUMN community.vocab_srs_item.next_due_at IS
  'Zeitpunkt, zu dem das Item wieder fällig ist.';
