CREATE TABLE guilds (
    id BYTEA NOT NULL PRIMARY KEY CHECK(length(id) = 26),

    -- Core identity
    name TEXT NOT NULL CHECK (LENGTH(name) >= 2 AND LENGTH(name) <= 100),
    description TEXT CHECK (LENGTH(COALESCE(description, '')) <= 1024),
    icon BYTEA CHECK(length(icon) = 26),
    banner BYTEA CHECK(length(banner) = 26),
    splash BYTEA CHECK(length(splash) = 26),

    -- Ownership & verification
    owner_id BYTEA NOT NULL CHECK(length(owner_id) = 26),
    owner_permissions BYTEA NOT NULL DEFAULT 'xFFFFFFFFFFFFFFFF'::BYTEA,  -- 8-byte bitmask (e.g., ADMINISTRATOR = 0x8)

    -- Regions & voice
    region TEXT NOT NULL DEFAULT 'us-west',  -- voice region (e.g., 'us-west', 'eu-central')

    -- Features (bitmask of enabled features)
    features INTEGER NOT NULL DEFAULT 0,  -- 0 = basic, 1 = ANIMATED_ICON, 2 = BANNER, 4 = COMMERCE, 8 = PUBLIC, etc.

    -- Discovery & visibility
    afk_channel_id BYTEA CHECK(length(afk_channel_id) = 26),
    afk_timeout INTEGER NOT NULL DEFAULT 300,  -- seconds (60, 300, 900, 1800, 3600)
    verification_level INTEGER NOT NULL DEFAULT 0,  -- 0 = none, 1 = low, 2 = medium, 3 = high, 4 = highest
    default_message_notifications INTEGER NOT NULL DEFAULT 1,  -- 0 = all, 1 = mentions only

    -- Explicit content filter
    explicit_content_filter INTEGER NOT NULL DEFAULT 0,  -- 0 = disabled, 1 = members without role, 2 = all

    -- System channels
    system_channel_id BYTEA CHECK(length(system_channel_id) = 26),
    system_channel_flags INTEGER NOT NULL DEFAULT 0,  -- 1 = SUPPRESS_JOIN_NOTIFICATIONS, 2 = SUPPRESS_PREMIUM_SUBSCRIPTIONS, etc.

    -- Boosting & nitro
    premium_boosters BYTEA[] NOT NULL DEFAULT ARRAY[]::BYTEA[],
    premium_tier INTEGER NOT NULL DEFAULT 0,  -- 0 = None, 1 = Tier 1, 2 = Tier 2, 3 = Tier 3
    premium_booster_count INTEGER NOT NULL DEFAULT 0,  -- cached boost count

    -- Safety & moderation
    widget_enabled BOOLEAN NOT NULL DEFAULT FALSE,
    widget_channel_id BYTEA CHECK(length(widget_channel_id) = 26),
    preferred_locale TEXT NOT NULL DEFAULT 'en-US',  -- IETF BCP 47 language tag

    -- Audit & integrity
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    large BOOLEAN NOT NULL DEFAULT FALSE,  -- >150 members
    member_count INTEGER NOT NULL DEFAULT 0  -- cached member count
);

-- Critical indexes
CREATE INDEX idx_guilds_owner_id ON guilds (owner_id);
CREATE INDEX idx_guilds_region ON guilds (region);
CREATE INDEX idx_guilds_verification_level ON guilds (verification_level);
CREATE INDEX idx_guilds_large ON guilds (large) WHERE large = TRUE;  -- for pagination
CREATE INDEX idx_guilds_created_at ON guilds (created_at DESC);