-- Montana Messenger relay schema (SQLite)
CREATE TABLE IF NOT EXISTS accounts (
    encryption_pubkey TEXT,
    account_id TEXT PRIMARY KEY,
    created_at_ms INTEGER NOT NULL,
    last_seen_at_ms INTEGER
);

CREATE TABLE IF NOT EXISTS sessions (
    token TEXT PRIMARY KEY,
    account_id TEXT NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
    expires_at_ms INTEGER NOT NULL,
    created_at_ms INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_sessions_account ON sessions(account_id);
CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at_ms);

CREATE TABLE IF NOT EXISTS messages (
    msg_id TEXT PRIMARY KEY,
    sender TEXT NOT NULL,
    recipient TEXT NOT NULL,
    ciphertext TEXT NOT NULL,
    nonce TEXT NOT NULL,
    created_at_ms INTEGER NOT NULL,
    read_at_ms INTEGER
);
CREATE INDEX IF NOT EXISTS idx_messages_recipient_time ON messages(recipient, created_at_ms DESC);
CREATE INDEX IF NOT EXISTS idx_messages_sender_time ON messages(sender, created_at_ms DESC);
CREATE INDEX IF NOT EXISTS idx_messages_pair_time ON messages(sender, recipient, created_at_ms DESC);

CREATE TABLE IF NOT EXISTS challenges (
    challenge_id TEXT PRIMARY KEY,
    account_id TEXT NOT NULL,
    challenge BLOB NOT NULL,
    expires_at_ms INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_challenges_expires ON challenges(expires_at_ms);

-- migration: добавить колонку если её ещё нет
