ALTER TABLE "servers" ADD COLUMN IF NOT EXISTS "anonymous_chat_allowed" boolean NOT NULL DEFAULT true;

CREATE TABLE IF NOT EXISTS "accounts" (
	"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
	"mc_uuid" text NOT NULL,
	"username" text NOT NULL,
	"auth_mode" text NOT NULL,
	"server_id" uuid REFERENCES "servers"("id") ON DELETE CASCADE,
	"created_at" timestamptz NOT NULL DEFAULT now()
);

-- Online accounts merge into one global identity per real Mojang UUID.
CREATE UNIQUE INDEX IF NOT EXISTS "accounts_online_uuid" ON "accounts" ("mc_uuid") WHERE "server_id" IS NULL;
-- Offline accounts are scoped to the one server that issued the uuid hash.
CREATE UNIQUE INDEX IF NOT EXISTS "accounts_offline_server_uuid" ON "accounts" ("server_id", "mc_uuid") WHERE "server_id" IS NOT NULL;

CREATE TABLE IF NOT EXISTS "sessions" (
	"token" text PRIMARY KEY NOT NULL,
	"account_id" uuid NOT NULL REFERENCES "accounts"("id") ON DELETE CASCADE,
	"created_at" timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS "chat_messages" (
	"id" bigserial PRIMARY KEY NOT NULL,
	"server_id" uuid NOT NULL REFERENCES "servers"("id") ON DELETE CASCADE,
	"username" text NOT NULL,
	"message" text NOT NULL,
	"source" text NOT NULL,
	"created_at" timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS "chat_messages_server_created_idx" ON "chat_messages" ("server_id", "created_at");
