SET @users_parent_path_exists := (
  SELECT COUNT(*) FROM information_schema.columns
  WHERE table_schema = DATABASE() AND table_name = 'users' AND column_name = 'parent_path'
);
SET @users_parent_path_sql := IF(
  @users_parent_path_exists = 0,
  'ALTER TABLE users ADD COLUMN parent_path VARCHAR(1024) NULL AFTER parent_id',
  'SELECT 1'
);
PREPARE users_parent_path_stmt FROM @users_parent_path_sql;
EXECUTE users_parent_path_stmt;
DEALLOCATE PREPARE users_parent_path_stmt;

SET @users_token_version_exists := (
  SELECT COUNT(*) FROM information_schema.columns
  WHERE table_schema = DATABASE() AND table_name = 'users' AND column_name = 'token_version'
);
SET @users_token_version_sql := IF(
  @users_token_version_exists = 0,
  'ALTER TABLE users ADD COLUMN token_version INT NOT NULL DEFAULT 0 AFTER parent_path',
  'SELECT 1'
);
PREPARE users_token_version_stmt FROM @users_token_version_sql;
EXECUTE users_token_version_stmt;
DEALLOCATE PREPARE users_token_version_stmt;

SET @users_must_change_password_exists := (
  SELECT COUNT(*) FROM information_schema.columns
  WHERE table_schema = DATABASE() AND table_name = 'users' AND column_name = 'must_change_password'
);
SET @users_must_change_password_sql := IF(
  @users_must_change_password_exists = 0,
  'ALTER TABLE users ADD COLUMN must_change_password TINYINT NOT NULL DEFAULT 0 AFTER token_version',
  'SELECT 1'
);
PREPARE users_must_change_password_stmt FROM @users_must_change_password_sql;
EXECUTE users_must_change_password_stmt;
DEALLOCATE PREPARE users_must_change_password_stmt;

SET @users_parent_path_index_exists := (
  SELECT COUNT(*) FROM information_schema.statistics
  WHERE table_schema = DATABASE() AND table_name = 'users' AND index_name = 'idx_users_parent_path'
);
SET @users_parent_path_index_sql := IF(
  @users_parent_path_index_exists = 0,
  'CREATE INDEX idx_users_parent_path ON users (parent_path(255))',
  'SELECT 1'
);
PREPARE users_parent_path_index_stmt FROM @users_parent_path_index_sql;
EXECUTE users_parent_path_index_stmt;
DEALLOCATE PREPARE users_parent_path_index_stmt;

UPDATE roles
SET permissions = JSON_OBJECT(
  '*', JSON_ARRAY('*'),
  'admin/users', JSON_ARRAY('read', 'write'),
  'admin/login-logs', JSON_ARRAY('read'),
  'admin/audit-logs', JSON_ARRAY('read'),
  'admin/permissions', JSON_ARRAY('read', 'write')
)
WHERE code = 'super_admin';

UPDATE roles
SET permissions = JSON_OBJECT(
  'admin/users', JSON_ARRAY('read', 'write')
)
WHERE code = 'agent';

UPDATE roles
SET permissions = JSON_OBJECT()
WHERE code = 'user';
