-- Restore merge-by-prosthesis uniqueness for lab case tasks.
-- Product rule: all teeth on a detail that share the same prosthesis type become
-- one task set (Scan/Design/…). selectionGroupId remains on the table for UI
-- but is not part of the unique key.
--
-- Drop the selectionGroupId-inclusive unique (by known names + by definition).

DO $$
DECLARE
  r RECORD;
BEGIN
  FOR r IN
    SELECT indexname
    FROM pg_indexes
    WHERE schemaname = 'public'
      AND tablename = 'lab_case_tasks'
      AND indexdef ILIKE '%UNIQUE%'
      AND indexdef ILIKE '%selectionGroupId%'
      AND indexdef ILIKE '%prosthesisTypeCode%'
      AND indexdef ILIKE '%stepOrder%'
  LOOP
    EXECUTE format('DROP INDEX IF EXISTS %I', r.indexname);
  END LOOP;
END $$;

DROP INDEX IF EXISTS "lab_case_tasks_labCaseId_treatmentDetailId_selectionGroupId_prosthesisTypeCode_stepOrder_key";

-- Collapse rows that were split by selectionGroupId but share the merge key
-- (status events cascade via FK). Kept row may need regen for full teeth[]; new sends are correct.
DELETE FROM "lab_case_tasks" AS a
  USING "lab_case_tasks" AS b
WHERE a."id" > b."id"
  AND a."labCaseId" = b."labCaseId"
  AND a."treatmentDetailId" = b."treatmentDetailId"
  AND a."prosthesisTypeCode" = b."prosthesisTypeCode"
  AND a."stepOrder" = b."stepOrder";

-- Short name stays under Postgres 63-char identifier limit.
CREATE UNIQUE INDEX IF NOT EXISTS "lab_case_tasks_case_detail_prosthesis_step_key"
  ON "lab_case_tasks"("labCaseId", "treatmentDetailId", "prosthesisTypeCode", "stepOrder");
