-- Practices attach to exactly one of: course, module, or lesson.
CREATE TABLE lms_practices (
    id BIGSERIAL PRIMARY KEY,
    course_id BIGINT REFERENCES courses (id) ON DELETE CASCADE,
    module_id BIGINT REFERENCES modules (id) ON DELETE CASCADE,
    lesson_id BIGINT REFERENCES lessons (id) ON DELETE CASCADE,
    title VARCHAR(255) NOT NULL,
    story_description TEXT,
    story_image TEXT,
    persona_id BIGINT REFERENCES users (id) ON DELETE SET NULL,
    question_set_id BIGINT NOT NULL REFERENCES question_sets (id) ON DELETE RESTRICT,
    quick_tips TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ,
    CONSTRAINT lms_practices_one_parent CHECK (
        (course_id IS NOT NULL)::int
        + (module_id IS NOT NULL)::int
        + (lesson_id IS NOT NULL)::int
        = 1
    )
);

CREATE INDEX idx_lms_practices_course_id ON lms_practices (course_id);
CREATE INDEX idx_lms_practices_module_id ON lms_practices (module_id);
CREATE INDEX idx_lms_practices_lesson_id ON lms_practices (lesson_id);
CREATE INDEX idx_lms_practices_question_set_id ON lms_practices (question_set_id);
CREATE INDEX idx_lms_practices_course_created ON lms_practices (course_id, created_at DESC);
CREATE INDEX idx_lms_practices_module_created ON lms_practices (module_id, created_at DESC);
CREATE INDEX idx_lms_practices_lesson_created ON lms_practices (lesson_id, created_at DESC);
