-- Treatment workflow steps + lab case tasks

CREATE TYPE "LabTaskStatus" AS ENUM ('PENDING', 'IN_PROGRESS', 'COMPLETED');

CREATE TABLE "treatment_workflow_steps" (
  "id" TEXT NOT NULL,
  "treatmentType" TEXT NOT NULL,
  "stepOrder" INTEGER NOT NULL,
  "label" TEXT NOT NULL,

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

CREATE UNIQUE INDEX "treatment_workflow_steps_treatmentType_stepOrder_key"
  ON "treatment_workflow_steps"("treatmentType", "stepOrder");

CREATE TABLE "lab_case_tasks" (
  "id" TEXT NOT NULL,
  "labCaseId" TEXT NOT NULL,
  "treatmentDetailId" TEXT NOT NULL,
  "tooth" TEXT NOT NULL,
  "treatmentType" TEXT NOT NULL,
  "stepOrder" INTEGER NOT NULL,
  "stepLabel" TEXT NOT NULL,
  "assigneeUserId" TEXT,
  "status" "LabTaskStatus" NOT NULL DEFAULT 'PENDING',

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

CREATE UNIQUE INDEX "lab_case_tasks_labCaseId_tooth_treatmentType_stepOrder_key"
  ON "lab_case_tasks"("labCaseId", "tooth", "treatmentType", "stepOrder");

CREATE INDEX "lab_case_tasks_labCaseId_status_idx" ON "lab_case_tasks"("labCaseId", "status");

ALTER TABLE "lab_case_tasks"
  ADD CONSTRAINT "lab_case_tasks_labCaseId_fkey"
  FOREIGN KEY ("labCaseId") REFERENCES "lab_cases"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "lab_case_tasks"
  ADD CONSTRAINT "lab_case_tasks_treatmentDetailId_fkey"
  FOREIGN KEY ("treatmentDetailId") REFERENCES "treatment_details"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "lab_case_tasks"
  ADD CONSTRAINT "lab_case_tasks_assigneeUserId_fkey"
  FOREIGN KEY ("assigneeUserId") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
