CREATE TABLE IF NOT EXISTS "servers" (
	"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
	"name" text NOT NULL,
	"token" text NOT NULL UNIQUE,
	"auth_mode" text NOT NULL DEFAULT 'offline',
	"created_at" timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS "chunk_columns" (
	"server_id" uuid NOT NULL REFERENCES "servers"("id") ON DELETE CASCADE,
	"dimension" integer NOT NULL,
	"x" integer NOT NULL,
	"z" integer NOT NULL,
	"block_id" integer NOT NULL,
	"block_meta" integer NOT NULL,
	"height" smallint NOT NULL,
	"updated_at" timestamptz NOT NULL DEFAULT now(),
	PRIMARY KEY ("server_id", "dimension", "x", "z")
);

CREATE TABLE IF NOT EXISTS "tile_pointers" (
	"server_id" uuid NOT NULL REFERENCES "servers"("id") ON DELETE CASCADE,
	"dimension" integer NOT NULL,
	"zoom" integer NOT NULL DEFAULT 0,
	"tile_x" integer NOT NULL,
	"tile_z" integer NOT NULL,
	"storage_key" text NOT NULL,
	"content_hash" text NOT NULL,
	"rendered_at" timestamptz NOT NULL DEFAULT now(),
	PRIMARY KEY ("server_id", "dimension", "zoom", "tile_x", "tile_z")
);

-- Chunk-granularity lookup: a live delta touches individual columns, but the worker re-renders
-- a whole chunk's 16x16 columns at once, keyed by floor(x/16), floor(z/16).
CREATE INDEX IF NOT EXISTS "chunk_columns_chunk_idx" ON "chunk_columns" (
	"server_id", "dimension", (floor("x" / 16.0)), (floor("z" / 16.0))
);
