-- Prosthesis type tree fields + multiple work items per tooth.

ALTER TABLE "prosthesis_types"
  ADD COLUMN IF NOT EXISTS "category" TEXT NOT NULL DEFAULT 'crown',
  ADD COLUMN IF NOT EXISTS "subcategory" TEXT NOT NULL DEFAULT '',
  ADD COLUMN IF NOT EXISTS "chartRegion" TEXT NOT NULL DEFAULT 'crown',
  ADD COLUMN IF NOT EXISTS "stackGroup" TEXT NOT NULL DEFAULT 'restoration',
  ADD COLUMN IF NOT EXISTS "addonKind" TEXT NOT NULL DEFAULT '';

ALTER TABLE "lab_case_tooth_prosthesis"
  DROP CONSTRAINT IF EXISTS "lab_case_tooth_prosthesis_labCaseId_sourceKey_tooth_key";

DROP INDEX IF EXISTS "lab_case_tooth_prosthesis_labCaseId_sourceKey_tooth_key";

-- Deduplicate stacked rows that would collide after adding prosthesisTypeCode to the unique key
-- (legacy unique already forbade two types per tooth, so this is a no-op for current data).
DELETE FROM "lab_case_tooth_prosthesis" AS a
  USING "lab_case_tooth_prosthesis" AS b
WHERE a."id" > b."id"
  AND a."labCaseId" = b."labCaseId"
  AND a."sourceKey" = b."sourceKey"
  AND a."tooth" = b."tooth"
  AND a."prosthesisTypeCode" = b."prosthesisTypeCode";

CREATE UNIQUE INDEX IF NOT EXISTS "lab_case_tooth_prosthesis_case_source_tooth_type_key"
  ON "lab_case_tooth_prosthesis"("labCaseId", "sourceKey", "tooth", "prosthesisTypeCode");
