-- Initial schema for My Linspirer MITM server

-- Global configuration
CREATE TABLE IF NOT EXISTS config (
    key TEXT PRIMARY KEY,
    value TEXT NOT NULL,
    description TEXT,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- Interception rules for JSON-RPC methods
CREATE TABLE IF NOT EXISTS interception_rules (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    method_name TEXT NOT NULL UNIQUE,
    action TEXT NOT NULL CHECK(action IN ('passthrough', 'modify', 'replace')),
    custom_response TEXT,
    is_enabled BOOLEAN DEFAULT 1,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- Template responses (for building custom_response)
CREATE TABLE IF NOT EXISTS response_templates (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL UNIQUE,
    method_name TEXT NOT NULL,
    response_json TEXT NOT NULL,
    description TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- Command queue persistence
CREATE TABLE IF NOT EXISTS commands (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    command_json TEXT NOT NULL,
    status TEXT NOT NULL CHECK(status IN ('unverified', 'verified', 'rejected')),
    received_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    processed_at DATETIME,
    notes TEXT
);

-- Index for performance
CREATE INDEX IF NOT EXISTS idx_commands_status ON commands(status);

-- Insert default config values
INSERT OR IGNORE INTO config (key, value, description) VALUES
    ('target_url', 'https://cloud.linspirer.com:883', 'Target server URL for proxying'),
    ('logging_enabled', 'true', 'Enable request/response logging'),
    ('log_retention_days', '7', 'Number of days to keep request logs');
