<?php

namespace Drupal\acquiadam_asset_import\Services;

/**
 * Utility service for Acquia DAM asset import operations.
 */
final class AssetImportUtilityService {

  /**
   * Decodes a category key from config storage.
   *
   * @param string $encoded_key
   *   The encoded category key.
   *
   * @return string
   *   The original category key.
   */
  public function decodeCategoryKey(string $encoded_key): string {
    // Decode the base64 encoded key.
    $decoded = base64_decode($encoded_key, TRUE);
    // If decoding fails (not a base64 string), return the original key.
    // This handles backward compatibility with existing unencoded keys.
    return $decoded !== FALSE ? $decoded : $encoded_key;
  }

  /**
   * Encodes configuration keys from plain text to base64 encoding.
   *
   * @param array $config_data
   *   The configuration data with plain text keys.
   *
   * @return array
   *   The configuration data with encoded keys.
   */
  public function encodeConfigKeys(array $config_data): array {
    $encoded_data = [];
    foreach ($config_data as $key => $value) {
      // Encode the key to make it safe for config storage.
      $encoded_key = base64_encode($key);
      $encoded_data[$encoded_key] = $value;
    }
    return $encoded_data;
  }

  /**
   * Decodes configuration keys from base64 encoding to plain text.
   *
   * @param array $config_data
   *   The configuration data with encoded keys.
   *
   * @return array
   *   The configuration data with decoded keys.
   */
  public function decodeConfigKeys(array $config_data): array {
    $decoded_data = [];
    foreach ($config_data as $encoded_key => $value) {
      // Decode the key back to original category name.
      $decoded_key = $this->decodeCategoryKey($encoded_key);
      $decoded_data[$decoded_key] = $value;
    }
    return $decoded_data;
  }

}

