CREATE TABLE api_tokens ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, token_prefix TEXT NOT NULL, secret_hash BYTEA NOT NULL, permissions JSONB NOT NULL DEFAULT '[]'::jsonb, mail_scope JSONB NOT NULL DEFAULT '{"all_accounts": true, "account_ids": []}'::jsonb, drive_scope JSONB NOT NULL DEFAULT '{"all_folders": true, "folder_paths": []}'::jsonb, expires_at TIMESTAMPTZ, last_used_at TIMESTAMPTZ, revoked_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE UNIQUE INDEX idx_api_tokens_prefix ON api_tokens(token_prefix) WHERE revoked_at IS NULL; CREATE INDEX idx_api_tokens_user ON api_tokens(user_id); CREATE INDEX idx_api_tokens_secret_hash ON api_tokens(secret_hash) WHERE revoked_at IS NULL;