<?php

/**
 * @file
 * Post update functions for Straker Translate.
 */

use Drupal\Core\Config\Entity\ConfigEntityUpdater;
use Drupal\straker_translate\StrakerTranslateProfileInterface;

/**
 * Update target custom profile settings with default value.
 */
function straker_translate_post_update_straker_translate_profile_target_save_to_vault(&$sandbox = NULL) {
  \Drupal::classResolver(ConfigEntityUpdater::class)
    ->update($sandbox, 'straker_translate_profile', function (StrakerTranslateProfileInterface $profile) {
      // Default target save-to vaults to default.
      $languages = \Drupal::languageManager()->getLanguages();
      foreach ($languages as $language) {
        $langcode = $language->getId();
        if ($profile->hasCustomSettingsForTarget($langcode)) {
          $profile->setVaultForTarget($langcode, 'default');
        }
      }
      return TRUE;
    });
}

/**
 * Remove obsolete Straker Translate account configuration.
 */
function straker_translate_post_update_delete_sandbox_host_settings() {
  \Drupal::configFactory()->getEditable('straker_translate.settings')
    ->clear('account.use_production')
    ->clear('account.sandbox_host')
    ->save();
}

/**
 * Implements hook_removed_post_updates().
 */
function straker_translate_removed_post_updates() {
  return [
    'straker_translate_post_update_straker_translate_manage_straker_translate_translations_permission' => '3.0.0',
    'straker_translate_post_update_straker_translate_metadata_dependencies' => '3.0.0',
    'straker_translate_post_update_straker_content_metadata_job_id' => '3.0.0',
    'straker_translate_post_update_straker_config_metadata_job_id' => '3.0.0',
    'straker_translate_post_update_straker_translate_profile_auto_request' => '3.0.0',
  ];
}
