-- Add TaggingJob table for background AI tagging
DO $$ BEGIN
    CREATE TYPE "TaggingJobStatus" AS ENUM ('PENDING', 'RUNNING', 'COMPLETED', 'FAILED');
EXCEPTION WHEN duplicate_object THEN NULL; END $$;

CREATE TABLE IF NOT EXISTS "TaggingJob" (
    "id" TEXT NOT NULL,
    "programId" TEXT,
    "roundId" TEXT,
    "status" "TaggingJobStatus" NOT NULL DEFAULT 'PENDING',
    "totalProjects" INTEGER NOT NULL DEFAULT 0,
    "processedCount" INTEGER NOT NULL DEFAULT 0,
    "taggedCount" INTEGER NOT NULL DEFAULT 0,
    "skippedCount" INTEGER NOT NULL DEFAULT 0,
    "failedCount" INTEGER NOT NULL DEFAULT 0,
    "errorMessage" TEXT,
    "errorsJson" JSONB,
    "startedAt" TIMESTAMP(3),
    "completedAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

CREATE INDEX IF NOT EXISTS "TaggingJob_programId_idx" ON "TaggingJob"("programId");
CREATE INDEX IF NOT EXISTS "TaggingJob_roundId_idx" ON "TaggingJob"("roundId");
CREATE INDEX IF NOT EXISTS "TaggingJob_status_idx" ON "TaggingJob"("status");

DO $$ BEGIN
    ALTER TABLE "TaggingJob" ADD CONSTRAINT "TaggingJob_programId_fkey"
        FOREIGN KEY ("programId") REFERENCES "Program"("id") ON DELETE CASCADE ON UPDATE CASCADE;
EXCEPTION WHEN duplicate_object THEN NULL; END $$;

DO $$ BEGIN
    ALTER TABLE "TaggingJob" ADD CONSTRAINT "TaggingJob_roundId_fkey"
        FOREIGN KEY ("roundId") REFERENCES "Round"("id") ON DELETE CASCADE ON UPDATE CASCADE;
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
