CREATE TABLE IF NOT EXISTS users ( id uuid PRIMARY KEY, username text NOT NULL UNIQUE, display_name text NOT NULL, password_hash text NOT NULL, created_at timestamptz NOT NULL ); CREATE TABLE IF NOT EXISTS sessions ( token_hash text PRIMARY KEY, user_id uuid NOT NULL REFERENCES users (id), expires_at timestamptz NOT NULL, revoked_at timestamptz ); CREATE INDEX IF NOT EXISTS sessions_user_id_idx ON sessions (user_id); CREATE TABLE IF NOT EXISTS chats ( id uuid PRIMARY KEY, title text NOT NULL, created_at timestamptz NOT NULL ); CREATE TABLE IF NOT EXISTS chat_members ( chat_id uuid NOT NULL REFERENCES chats (id), user_id uuid NOT NULL REFERENCES users (id), position integer NOT NULL, PRIMARY KEY (chat_id, user_id) ); CREATE INDEX IF NOT EXISTS chat_members_user_idx ON chat_members (user_id, chat_id); CREATE TABLE IF NOT EXISTS attachments ( id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats (id), owner_id uuid NOT NULL REFERENCES users (id), filename text NOT NULL, content_type text NOT NULL, size_bytes integer NOT NULL CHECK (size_bytes > 0 AND size_bytes <= 10485760), sha256 text NOT NULL, status text NOT NULL CHECK (status = 'ready'), object_key text NOT NULL UNIQUE, error_code text, created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL ); CREATE INDEX IF NOT EXISTS attachments_chat_idx ON attachments (chat_id, created_at); CREATE TABLE IF NOT EXISTS messages ( id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats (id), sender_id uuid NOT NULL REFERENCES users (id), text text NOT NULL, created_at timestamptz NOT NULL ); CREATE INDEX IF NOT EXISTS messages_chat_order_idx ON messages (chat_id, created_at, id); CREATE TABLE IF NOT EXISTS message_attachments ( message_id uuid NOT NULL REFERENCES messages (id), attachment_id uuid NOT NULL REFERENCES attachments (id), position integer NOT NULL, PRIMARY KEY (message_id, position) ); CREATE INDEX IF NOT EXISTS message_attachments_attachment_idx ON message_attachments (attachment_id); CREATE TABLE IF NOT EXISTS idempotency ( user_id uuid NOT NULL REFERENCES users (id), http_method text NOT NULL, path text NOT NULL, idem_key text NOT NULL, request_hash text NOT NULL, status_code integer NOT NULL, response_json jsonb NOT NULL, created_at timestamptz NOT NULL, PRIMARY KEY (user_id, http_method, path, idem_key) ); CREATE TABLE IF NOT EXISTS object_ledger ( object_key text PRIMARY KEY, attachment_id uuid, chat_id uuid, state text NOT NULL CHECK (state IN ('staging', 'committed', 'aborted', 'purged')), note text, size_bytes bigint, created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL ); CREATE INDEX IF NOT EXISTS object_ledger_state_idx ON object_ledger (state, created_at);