-- Phase 6: Multi-node scheduling, start queue, node capacity

CREATE TYPE "StartQueueStatus" AS ENUM ('QUEUED', 'DISPATCHED', 'CANCELLED', 'EXPIRED');

ALTER TYPE "GameServerStatus" ADD VALUE IF NOT EXISTS 'QUEUED';
ALTER TYPE "GameServerStatus" ADD VALUE IF NOT EXISTS 'UNKNOWN';

ALTER TABLE "game_nodes"
  ADD COLUMN IF NOT EXISTS "maxRamMb" INTEGER NOT NULL DEFAULT 16384,
  ADD COLUMN IF NOT EXISTS "platformRamMb" INTEGER NOT NULL DEFAULT 2048,
  ADD COLUMN IF NOT EXISTS "drainRequestedAt" TIMESTAMPTZ(3);

CREATE TABLE "server_start_queue" (
  "id" TEXT NOT NULL,
  "serverId" TEXT NOT NULL,
  "nodeId" TEXT NOT NULL,
  "status" "StartQueueStatus" NOT NULL DEFAULT 'QUEUED',
  "priority" INTEGER NOT NULL DEFAULT 0,
  "correlationId" TEXT,
  "requestedAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "expiresAt" TIMESTAMPTZ(3),
  "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updatedAt" TIMESTAMPTZ(3) NOT NULL,

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

CREATE UNIQUE INDEX "server_start_queue_serverId_key" ON "server_start_queue"("serverId");
CREATE INDEX "server_start_queue_status_priority_requestedAt_idx" ON "server_start_queue"("status", "priority", "requestedAt");
CREATE INDEX "server_start_queue_nodeId_idx" ON "server_start_queue"("nodeId");

ALTER TABLE "server_start_queue"
  ADD CONSTRAINT "server_start_queue_serverId_fkey"
  FOREIGN KEY ("serverId") REFERENCES "game_servers"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "server_start_queue"
  ADD CONSTRAINT "server_start_queue_nodeId_fkey"
  FOREIGN KEY ("nodeId") REFERENCES "game_nodes"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
