-- Treatment type catalog (data-driven; business logic reads from here)

CREATE TABLE "treatment_types" (
  "id" TEXT NOT NULL,
  "code" TEXT NOT NULL,
  "labDependent" BOOLEAN NOT NULL DEFAULT false,
  "sortOrder" INTEGER NOT NULL DEFAULT 0,

  CONSTRAINT "treatment_types_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX "treatment_types_code_key" ON "treatment_types"("code");

-- Temporary catalog (will be replaced with 14 real-world types later)
INSERT INTO "treatment_types" ("id", "code", "labDependent", "sortOrder") VALUES
  ('tt-consultation', 'consultation', false, 1),
  ('tt-filling', 'filling', false, 2),
  ('tt-endo', 'endo', true, 3),
  ('tt-visit', 'visit', false, 4),
  ('tt-hygiene', 'hygiene', false, 5);

-- Re-link workflow steps to catalog rows
ALTER TABLE "treatment_workflow_steps" ADD COLUMN "treatmentTypeId" TEXT;

UPDATE "treatment_workflow_steps" AS w
SET "treatmentTypeId" = t."id"
FROM "treatment_types" AS t
WHERE t."code" = w."treatmentType";

-- Drop steps for clinic-only types; only lab-dependent types keep workflows
DELETE FROM "treatment_workflow_steps" AS w
USING "treatment_types" AS t
WHERE w."treatmentTypeId" = t."id" AND t."labDependent" = false;

DELETE FROM "treatment_workflow_steps" WHERE "treatmentTypeId" IS NULL;

ALTER TABLE "treatment_workflow_steps" DROP CONSTRAINT IF EXISTS "treatment_workflow_steps_treatmentType_stepOrder_key";
DROP INDEX IF EXISTS "treatment_workflow_steps_treatmentType_stepOrder_key";

ALTER TABLE "treatment_workflow_steps" DROP COLUMN "treatmentType";

ALTER TABLE "treatment_workflow_steps" ALTER COLUMN "treatmentTypeId" SET NOT NULL;

ALTER TABLE "treatment_workflow_steps"
  ADD CONSTRAINT "treatment_workflow_steps_treatmentTypeId_fkey"
  FOREIGN KEY ("treatmentTypeId") REFERENCES "treatment_types"("id") ON DELETE CASCADE ON UPDATE CASCADE;

CREATE UNIQUE INDEX "treatment_workflow_steps_treatmentTypeId_stepOrder_key"
  ON "treatment_workflow_steps"("treatmentTypeId", "stepOrder");
