-- Lab case activity feed + per-user read cursors for tab badges

CREATE TYPE "LabCaseActivityType" AS ENUM (
  'CASE_SENT',
  'CLINIC_COMMENT',
  'LAB_COMMENT',
  'CASE_IMPORTANT',
  'CASE_AMENDED',
  'TASK_COMPLETED'
);

CREATE TYPE "LabCaseTabReadTarget" AS ENUM ('CASES', 'TASKS', 'TREATMENT');

CREATE TABLE "lab_case_activities" (
  "id" TEXT NOT NULL,
  "labCaseId" TEXT NOT NULL,
  "type" "LabCaseActivityType" NOT NULL,
  "actorUserId" TEXT,
  "payload" JSONB,
  "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT "lab_case_activities_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "lab_case_user_read_states" (
  "userId" TEXT NOT NULL,
  "organizationId" TEXT NOT NULL,
  "labCaseId" TEXT NOT NULL,
  "lastReadAt" TIMESTAMP(3) NOT NULL,
  CONSTRAINT "lab_case_user_read_states_pkey" PRIMARY KEY ("userId", "organizationId", "labCaseId")
);

CREATE TABLE "lab_case_user_tab_read_states" (
  "userId" TEXT NOT NULL,
  "organizationId" TEXT NOT NULL,
  "tab" "LabCaseTabReadTarget" NOT NULL,
  "lastReadAt" TIMESTAMP(3) NOT NULL,
  CONSTRAINT "lab_case_user_tab_read_states_pkey" PRIMARY KEY ("userId", "organizationId", "tab")
);

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

ALTER TABLE "lab_case_activities"
  ADD CONSTRAINT "lab_case_activities_actorUserId_fkey"
  FOREIGN KEY ("actorUserId") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;

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

CREATE INDEX "lab_case_activities_labCaseId_createdAt_idx"
  ON "lab_case_activities"("labCaseId", "createdAt");

CREATE INDEX "lab_case_activities_type_createdAt_idx"
  ON "lab_case_activities"("type", "createdAt");

CREATE INDEX "lab_case_user_read_states_userId_organizationId_idx"
  ON "lab_case_user_read_states"("userId", "organizationId");
