-- Add ProjectTag table for AI tagging
CREATE TABLE IF NOT EXISTS "ProjectTag" (
    "id" TEXT NOT NULL,
    "projectId" TEXT NOT NULL,
    "tagId" TEXT NOT NULL,
    "confidence" DOUBLE PRECISION NOT NULL DEFAULT 1.0,
    "source" TEXT NOT NULL DEFAULT 'AI',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT "ProjectTag_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX IF NOT EXISTS "ProjectTag_projectId_tagId_key" ON "ProjectTag"("projectId", "tagId");
CREATE INDEX IF NOT EXISTS "ProjectTag_projectId_idx" ON "ProjectTag"("projectId");
CREATE INDEX IF NOT EXISTS "ProjectTag_tagId_idx" ON "ProjectTag"("tagId");

DO $$ BEGIN
    ALTER TABLE "ProjectTag" ADD CONSTRAINT "ProjectTag_projectId_fkey"
        FOREIGN KEY ("projectId") REFERENCES "Project"("id") ON DELETE CASCADE ON UPDATE CASCADE;
EXCEPTION WHEN duplicate_object THEN NULL; END $$;

DO $$ BEGIN
    ALTER TABLE "ProjectTag" ADD CONSTRAINT "ProjectTag_tagId_fkey"
        FOREIGN KEY ("tagId") REFERENCES "ExpertiseTag"("id") ON DELETE CASCADE ON UPDATE CASCADE;
EXCEPTION WHEN duplicate_object THEN NULL; END $$;

-- Add AssignmentJob table for AI assignment progress tracking
DO $$ BEGIN
    CREATE TYPE "AssignmentJobStatus" AS ENUM ('PENDING', 'RUNNING', 'COMPLETED', 'FAILED');
EXCEPTION WHEN duplicate_object THEN NULL; END $$;

CREATE TABLE IF NOT EXISTS "AssignmentJob" (
    "id" TEXT NOT NULL,
    "roundId" TEXT NOT NULL,
    "status" "AssignmentJobStatus" NOT NULL DEFAULT 'PENDING',
    "totalProjects" INTEGER NOT NULL DEFAULT 0,
    "totalBatches" INTEGER NOT NULL DEFAULT 0,
    "currentBatch" INTEGER NOT NULL DEFAULT 0,
    "processedCount" INTEGER NOT NULL DEFAULT 0,
    "suggestionsCount" INTEGER NOT NULL DEFAULT 0,
    "errorMessage" TEXT,
    "startedAt" TIMESTAMP(3),
    "completedAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "fallbackUsed" BOOLEAN NOT NULL DEFAULT false,
    CONSTRAINT "AssignmentJob_pkey" PRIMARY KEY ("id")
);

CREATE INDEX IF NOT EXISTS "AssignmentJob_roundId_idx" ON "AssignmentJob"("roundId");
CREATE INDEX IF NOT EXISTS "AssignmentJob_status_idx" ON "AssignmentJob"("status");

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