SET @users_parent_id_exists := (
  SELECT COUNT(*)
  FROM information_schema.columns
  WHERE table_schema = DATABASE()
    AND table_name = 'users'
    AND column_name = 'parent_id'
);
SET @users_parent_id_sql := IF(
  @users_parent_id_exists = 0,
  'ALTER TABLE users ADD COLUMN parent_id VARCHAR(36) NULL AFTER enabled',
  'SELECT 1'
);
PREPARE users_parent_id_stmt FROM @users_parent_id_sql;
EXECUTE users_parent_id_stmt;
DEALLOCATE PREPARE users_parent_id_stmt;

SET @users_parent_id_index_exists := (
  SELECT COUNT(*)
  FROM information_schema.statistics
  WHERE table_schema = DATABASE()
    AND table_name = 'users'
    AND index_name = 'idx_users_parent_id'
);
SET @users_parent_id_index_sql := IF(
  @users_parent_id_index_exists = 0,
  'CREATE INDEX idx_users_parent_id ON users (parent_id)',
  'SELECT 1'
);
PREPARE users_parent_id_index_stmt FROM @users_parent_id_index_sql;
EXECUTE users_parent_id_index_stmt;
DEALLOCATE PREPARE users_parent_id_index_stmt;

INSERT INTO roles (id, code, name, permissions)
SELECT
  '60e6fb3f-7b03-4e37-a4c1-1690c7aabf01',
  'agent',
  '代理',
  JSON_OBJECT('admin/users', JSON_ARRAY('read', 'write'))
WHERE NOT EXISTS (SELECT 1 FROM roles WHERE code = 'agent');

INSERT INTO roles (id, code, name, permissions)
SELECT
  'c6805ef4-bc20-4ec8-93a7-2e8ea1b33677',
  'user',
  '普通用户',
  JSON_OBJECT()
WHERE NOT EXISTS (SELECT 1 FROM roles WHERE code = 'user');
