-- Learn English: at most one lms_practice per course, module, or lesson parent.
-- Remove duplicate rows (keep the earliest practice per parent) before adding constraints.
DELETE FROM lms_practices a
USING lms_practices b
WHERE a.course_id IS NOT NULL
  AND a.course_id = b.course_id
  AND a.id > b.id;

DELETE FROM lms_practices a
USING lms_practices b
WHERE a.module_id IS NOT NULL
  AND a.module_id = b.module_id
  AND a.id > b.id;

DELETE FROM lms_practices a
USING lms_practices b
WHERE a.lesson_id IS NOT NULL
  AND a.lesson_id = b.lesson_id
  AND a.id > b.id;

CREATE UNIQUE INDEX idx_lms_practices_one_per_course
    ON lms_practices (course_id)
    WHERE course_id IS NOT NULL;

CREATE UNIQUE INDEX idx_lms_practices_one_per_module
    ON lms_practices (module_id)
    WHERE module_id IS NOT NULL;

CREATE UNIQUE INDEX idx_lms_practices_one_per_lesson
    ON lms_practices (lesson_id)
    WHERE lesson_id IS NOT NULL;
