CREATE TABLE IF NOT EXISTS users(id uuid PRIMARY KEY, username text NOT NULL UNIQUE, password text NOT NULL, doc jsonb NOT NULL); CREATE TABLE IF NOT EXISTS sessions(token text PRIMARY KEY, user_id uuid NOT NULL REFERENCES users, expires_at timestamptz NOT NULL); CREATE TABLE IF NOT EXISTS chats(id uuid PRIMARY KEY, doc jsonb NOT NULL); CREATE TABLE IF NOT EXISTS messages(id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats, sender_id uuid NOT NULL REFERENCES users, idem_key text NOT NULL, body jsonb NOT NULL, doc jsonb NOT NULL, saved_at timestamptz NOT NULL DEFAULT now()); CREATE INDEX IF NOT EXISTS messages_replay ON messages(sender_id,chat_id,idem_key,saved_at); CREATE INDEX IF NOT EXISTS messages_page ON messages(chat_id,(doc->>'created_at'),id); CREATE TABLE IF NOT EXISTS attachments(id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats, doc jsonb NOT NULL, stage_key text); ALTER TABLE attachments ADD COLUMN IF NOT EXISTS stage_key text; CREATE TABLE IF NOT EXISTS attachment_jobs( job_id uuid PRIMARY KEY, attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id), payload jsonb NOT NULL, status text NOT NULL DEFAULT 'queued' CHECK(status IN ('queued','processing','done','failed')), attempt integer NOT NULL DEFAULT 0, published_at timestamptz, last_error text, created_at timestamptz NOT NULL DEFAULT now() ); CREATE INDEX IF NOT EXISTS attachment_jobs_outbox ON attachment_jobs(created_at) WHERE published_at IS NULL; CREATE TABLE IF NOT EXISTS login_rate_limits( key_hash text PRIMARY KEY, window_started timestamptz NOT NULL, failures integer NOT NULL CHECK(failures>=0) );