-- Initialize multi-user database with API keys
-- First ensure the api_keys table exists
CREATE TABLE IF NOT EXISTS api_keys (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id TEXT NOT NULL UNIQUE,
    key_hash TEXT NOT NULL UNIQUE,
    admin BOOLEAN NOT NULL DEFAULT FALSE,
    roles TEXT NOT NULL DEFAULT '[]',
    permissions TEXT NOT NULL DEFAULT '{}',
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    expires_at DATETIME,
    revoked_at DATETIME,
    CHECK (json_valid(roles)),
    CHECK (json_valid(permissions))
);

-- Insert admin user with full permissions
INSERT OR REPLACE INTO api_keys (user_id, key_hash, admin, roles, permissions) 
VALUES ('admin_user', '5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8', TRUE, '["user", "admin"]', '{"read": true, "write": true, "delete": true}');

-- Insert researcher with read/write permissions
INSERT OR REPLACE INTO api_keys (user_id, key_hash, admin, roles, permissions) 
VALUES ('researcher1', 'ef92b778ba7a6c8f2150019a5678047b6a9a2b95cef8189518f9b35c54d2e3ae', FALSE, '["user", "researcher"]', '{"read": true, "write": true, "delete": false}');

-- Insert analyst with read-only permissions
INSERT OR REPLACE INTO api_keys (user_id, key_hash, admin, roles, permissions) 
VALUES ('analyst1', 'a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3', FALSE, '["user", "analyst"]', '{"read": true, "write": false, "delete": false}');
