-- Phase 8: DNS metadata and join-to-start

CREATE TYPE "DnsRecordStatus" AS ENUM ('PENDING', 'ACTIVE', 'FAILED', 'REMOVED');

ALTER TABLE "game_servers"
  ADD COLUMN IF NOT EXISTS "joinSlug" TEXT,
  ADD COLUMN IF NOT EXISTS "joinToStartEnabled" BOOLEAN NOT NULL DEFAULT true;

CREATE UNIQUE INDEX IF NOT EXISTS "game_servers_joinSlug_key" ON "game_servers"("joinSlug");

ALTER TABLE "game_nodes"
  ADD COLUMN IF NOT EXISTS "portRangeStart" INTEGER NOT NULL DEFAULT 25565,
  ADD COLUMN IF NOT EXISTS "portRangeEnd" INTEGER NOT NULL DEFAULT 25664;

CREATE TABLE IF NOT EXISTS "server_dns_records" (
  "id" TEXT NOT NULL,
  "serverId" TEXT NOT NULL,
  "fqdn" TEXT NOT NULL,
  "recordType" TEXT NOT NULL,
  "target" TEXT NOT NULL,
  "port" INTEGER,
  "srvPriority" INTEGER,
  "srvWeight" INTEGER,
  "status" "DnsRecordStatus" NOT NULL DEFAULT 'PENDING',
  "lastSyncedAt" TIMESTAMPTZ(3),
  "lastError" TEXT,
  "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updatedAt" TIMESTAMPTZ(3) NOT NULL,

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

CREATE UNIQUE INDEX IF NOT EXISTS "server_dns_records_serverId_recordType_fqdn_key"
  ON "server_dns_records"("serverId", "recordType", "fqdn");

CREATE INDEX IF NOT EXISTS "server_dns_records_fqdn_idx" ON "server_dns_records"("fqdn");

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