<?php

/**
 * @file
 * Post updates for the Native Observability module.
 */

declare(strict_types=1);

/**
 * Uninstalls obsolete Native Observability submodules before code cleanup.
 *
 * Important:
 * - This post-update only uninstalls deprecated modules from Drupal.
 * - Physical module directories must be removed separately during deployment.
 * - Deprecated module folders should be excluded from the current commit until
 *   the cleanup deploy step is executed.
 */
function native_observability_post_update_uninstall_obsolete_submodules(array &$sandbox = []): string {
  $obsolete_modules = [
    'native_observability_drush',
    'native_observability_logging',
  ];

  $module_handler = \Drupal::moduleHandler();
  $module_installer = \Drupal::service('module_installer');

  $installed_modules = [];

  foreach ($obsolete_modules as $module) {
    if ($module_handler->moduleExists($module)) {
      $installed_modules[] = $module;
    }
  }

  if ($installed_modules === []) {
    return 'No obsolete Native Observability submodules were installed.';
  }

  $module_installer->uninstall($installed_modules, TRUE);

  return 'Uninstalled obsolete submodules: ' . implode(', ', $installed_modules) . '. '
    . 'Remove their directories separately during deployment.';
}
