-- One LabCaseTask pipeline per tooth: unique must include tooth.
ALTER TABLE "lab_case_tasks" ADD COLUMN IF NOT EXISTS "tooth" TEXT NOT NULL DEFAULT '';

UPDATE "lab_case_tasks"
SET "tooth" = COALESCE("teeth"->>0, '')
WHERE "tooth" = '';

ALTER TABLE "lab_case_tasks" DROP CONSTRAINT IF EXISTS "lab_case_tasks_case_source_prosthesis_step_key";
DROP INDEX IF EXISTS "lab_case_tasks_case_source_prosthesis_step_key";

CREATE UNIQUE INDEX IF NOT EXISTS "lab_case_tasks_case_source_tooth_prosthesis_step_key"
  ON "lab_case_tasks"("labCaseId", "sourceKey", "tooth", "prosthesisTypeCode", "stepOrder");
