-- ============================================================================
-- Auth Database Schema (auth.db)
-- ============================================================================
-- Separate from medical data (inou.db). Volatile/ephemeral data.
-- ============================================================================

-- Sessions table for secure session management
-- Tokens are random 32-byte base64url-encoded strings
CREATE TABLE IF NOT EXISTS sessions (
    token TEXT PRIMARY KEY,
    dossier_id TEXT NOT NULL,
    created_at INTEGER NOT NULL,
    expires_at INTEGER NOT NULL
);

-- Index for fast session lookup and cleanup
CREATE INDEX IF NOT EXISTS idx_sessions_dossier ON sessions(dossier_id);
CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at);

-- OAuth authorization codes (PKCE, 10 min expiry)
CREATE TABLE IF NOT EXISTS oauth_codes (
    code TEXT PRIMARY KEY,
    client_id TEXT NOT NULL,
    dossier_id TEXT NOT NULL,
    redirect_uri TEXT NOT NULL,
    code_challenge TEXT,
    code_challenge_method TEXT,
    expires_at INTEGER NOT NULL,
    used INTEGER DEFAULT 0
);

-- OAuth refresh tokens (30 day expiry)
CREATE TABLE IF NOT EXISTS oauth_refresh_tokens (
    token_id TEXT PRIMARY KEY,
    client_id TEXT NOT NULL,
    dossier_id TEXT NOT NULL,
    created_at INTEGER NOT NULL,
    expires_at INTEGER NOT NULL,
    revoked INTEGER DEFAULT 0
);

-- OAuth clients (registered applications)
CREATE TABLE IF NOT EXISTS oauth_clients (
    client_id TEXT PRIMARY KEY,
    client_secret TEXT,
    name TEXT NOT NULL,
    redirect_uris TEXT NOT NULL,  -- JSON array
    allowed_scopes TEXT,           -- JSON array
    created_at INTEGER NOT NULL
);

-- Cleanup old sessions periodically
DELETE FROM sessions WHERE expires_at < strftime('%s', 'now');
DELETE FROM oauth_codes WHERE expires_at < strftime('%s', 'now');
DELETE FROM oauth_refresh_tokens WHERE expires_at < strftime('%s', 'now');
