-- Users table
CREATE TABLE IF NOT EXISTS users (
    id TEXT PRIMARY KEY,
    username TEXT UNIQUE NOT NULL,
    email TEXT,
    password_hash TEXT,
    role TEXT NOT NULL DEFAULT 'viewer',
    provider TEXT NOT NULL DEFAULT 'local',
    provider_id TEXT,
    created_at DATETIME NOT NULL,
    last_login DATETIME,
    is_active BOOLEAN NOT NULL DEFAULT true
);

-- Sessions table
CREATE TABLE IF NOT EXISTS sessions (
    id TEXT PRIMARY KEY,
    user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    token TEXT UNIQUE NOT NULL,
    created_at DATETIME NOT NULL,
    expires_at DATETIME NOT NULL,
    is_active BOOLEAN NOT NULL DEFAULT true
);

-- Access rules table for path-based permissions
CREATE TABLE IF NOT EXISTS access_rules (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    path_pattern TEXT NOT NULL,
    required_role TEXT NOT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- Create indexes (SQLite ignores IF NOT EXISTS for indexes, so we'll use a different approach)
CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
CREATE INDEX IF NOT EXISTS idx_users_provider ON users(provider, provider_id);
CREATE INDEX IF NOT EXISTS idx_sessions_token ON sessions(token);
CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id);
CREATE INDEX IF NOT EXISTS idx_sessions_expires_at ON sessions(expires_at);
CREATE INDEX IF NOT EXISTS idx_access_rules_path ON access_rules(path_pattern);

-- Insert default admin user (password: admin123) - only if it doesn't exist
INSERT OR IGNORE INTO users (
    id, 
    username, 
    email, 
    password_hash, 
    role, 
    provider, 
    created_at, 
    is_active
) VALUES (
    '550e8400-e29b-41d4-a716-446655440000',
    'admin',
    'admin@obswiki.local',
    '$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/Xh4XoKjKS6J8G7/gS',
    'admin',
    'local',
    '2024-01-01 00:00:00',
    true
);

-- Insert some default access rules - only if they don't exist
INSERT OR IGNORE INTO access_rules (id, path_pattern, required_role) VALUES
    (1, 'admin/*', 'admin'),
    (2, 'private/*', 'editor'),
    (3, '*', 'viewer');