-- C Nostr Relay Database Schema
-- Simplified schema with just event and tag tables
-- SQLite database for storing Nostr events

-- ============================================================================
-- DATABASE SETTINGS
-- ============================================================================

PRAGMA encoding = "UTF-8";
PRAGMA journal_mode = WAL;
PRAGMA auto_vacuum = FULL;
PRAGMA synchronous = NORMAL;
PRAGMA foreign_keys = ON;

-- ============================================================================
-- EVENT TABLE
-- ============================================================================

-- Main event table - stores all Nostr events
CREATE TABLE IF NOT EXISTS event (
    id TEXT PRIMARY KEY,                -- Nostr event ID (hex string)
    pubkey TEXT NOT NULL,               -- Public key of event author (hex string)
    created_at INTEGER NOT NULL,       -- Event creation timestamp (Unix timestamp)
    kind INTEGER NOT NULL,              -- Event kind (0-65535)
    content TEXT NOT NULL,              -- Event content (text content only)
    sig TEXT NOT NULL                   -- Event signature (hex string)
);

-- Event indexes for performance
CREATE INDEX IF NOT EXISTS event_pubkey_index ON event(pubkey);
CREATE INDEX IF NOT EXISTS event_created_at_index ON event(created_at);
CREATE INDEX IF NOT EXISTS event_kind_index ON event(kind);
CREATE INDEX IF NOT EXISTS event_pubkey_created_at_index ON event(pubkey, created_at);
CREATE INDEX IF NOT EXISTS event_kind_created_at_index ON event(kind, created_at);

-- ============================================================================
-- TAG TABLE
-- ============================================================================

-- Tag table for storing event tags
CREATE TABLE IF NOT EXISTS tag (
    id TEXT NOT NULL,                       -- Nostr event ID (references event.id)
    name TEXT NOT NULL,                     -- Tag name (e.g., "e", "p", "d")
    value TEXT NOT NULL,                    -- Tag value
    parameters TEXT,                        -- Additional tag parameters (JSON string)
    FOREIGN KEY(id) REFERENCES event(id) ON UPDATE CASCADE ON DELETE CASCADE
);

-- Tag indexes for performance
CREATE INDEX IF NOT EXISTS tag_id_index ON tag(id);
CREATE INDEX IF NOT EXISTS tag_name_index ON tag(name);
CREATE INDEX IF NOT EXISTS tag_name_value_index ON tag(name, value);
CREATE INDEX IF NOT EXISTS tag_id_name_index ON tag(id, name);

-- ============================================================================
-- PERFORMANCE OPTIMIZATIONS
-- ============================================================================

-- Enable query planner optimizations
PRAGMA optimize;

-- Set recommended pragmas for performance
PRAGMA main.synchronous = NORMAL;
PRAGMA foreign_keys = ON;
PRAGMA temp_store = 2;              -- use memory for temp tables
PRAGMA main.cache_size = 10000;     -- 40MB cache per connection