-- AlterTable: add nullable category column to EvaluationForm
ALTER TABLE "EvaluationForm" ADD COLUMN IF NOT EXISTS "category" "CompetitionCategory";

-- Drop old unique constraint (IF EXISTS — may not exist on fresh databases where
-- the constraint was never created or was already removed by an earlier migration)
ALTER TABLE "EvaluationForm" DROP CONSTRAINT IF EXISTS "EvaluationForm_roundId_version_key";

-- Add new unique constraint including category
ALTER TABLE "EvaluationForm" DROP CONSTRAINT IF EXISTS "EvaluationForm_roundId_version_category_key";
ALTER TABLE "EvaluationForm" ADD CONSTRAINT "EvaluationForm_roundId_version_category_key" UNIQUE ("roundId", "version", "category");

-- Partial unique index: prevent duplicate shared forms at the same version
-- (PostgreSQL treats NULLs as distinct in unique constraints, so we need this)
DROP INDEX IF EXISTS "EvaluationForm_roundId_version_null_category";
CREATE UNIQUE INDEX "EvaluationForm_roundId_version_null_category"
  ON "EvaluationForm" ("roundId", "version") WHERE "category" IS NULL;

-- Compound index for category-aware active form lookups
DROP INDEX IF EXISTS "EvaluationForm_roundId_isActive_category_idx";
CREATE INDEX "EvaluationForm_roundId_isActive_category_idx"
  ON "EvaluationForm" ("roundId", "isActive", "category");
