<?php

/**
 * @file
 * Contains hook implementations for sobki_profile_bootstrap profile.
 */

declare(strict_types=1);

/**
 * Implements hook_install_tasks().
 */
function sobki_profile_bootstrap_install_tasks(array &$install_state): array {
  return [
    'sobki_profile_bootstrap_enable_default_content' => [],
    'sobki_profile_bootstrap_set_front_page' => [],
  ];
}

/**
 * Enable default content module.
 *
 * Done in an installation task to avoid to introduce a hook_install in the
 * installation profile. And therefore to avoid the core bug:
 * https://www.drupal.org/project/drupal/issues/2982052
 *
 * Not possible to add the module in .info.yml file as the configuration needs
 * to be imported before.
 *
 * @param array $install_state
 *   An array of information about the current installation state.
 */
function sobki_profile_bootstrap_enable_default_content(array &$install_state): void {
  /** @var \Drupal\Core\Extension\ModuleInstallerInterface $module_installer */
  $module_installer = \Drupal::service('module_installer');
  $module_installer->install([
    'sobki_default_content',
  ]);
}

/**
 * Set front page.
 *
 * Executed after default content module installation so it is possible to load
 * the home node to get its ID.
 *
 * @param array $install_state
 *   An array of information about the current installation state.
 */
function sobki_profile_bootstrap_set_front_page(array &$install_state): void {
  $uuid = '5606505e-cd84-426f-8aee-d56ef86e8935';
  $nodes = \Drupal::entityTypeManager()->getStorage('node')
    ->loadByProperties([
      'uuid' => $uuid,
    ]);

  if (empty($nodes)) {
    \Drupal::logger('sobki_profile_bootstrap')
      ->warning('The node with the UUID @uuid cannot be found. Impossible to set it as front page.', [
        '@uuid' => $uuid,
      ]);
    return;
  }

  /** @var \Drupal\node\NodeInterface $node */
  $node = \array_shift($nodes);

  \Drupal::configFactory()->getEditable('system.site')
    ->set('page.front', '/node/' . $node->id())
    ->save();
}
