<?php

/**
 * @file
 * Implements migration helpers in deploy hook to help migrate images to media.
 *
 * Config updates in drutopia utilize media entities for storing images.
 */

use Psr\Log\LogLevel;

/**
 * Move data from image fields to media entity reference fields.
 *
 * Implements hook_deploy_NAME().
 */
function geo_upgrade_deploy_move_images_to_media() {
  $transformations = [
    ['paragraph', ['field_image'], 'field_media_image', ['image', 'slide']],
    ['node', ['field_image'], 'field_media_image', ['people', 'article', 'blog', 'collection', 'gleaning']],
    // Leaving out the following for now, unless requested later
    // ['paragraph', ['field_file'], 'field_media_document', ['file']],
    // field_media_document would need to be created on file paragraph
    // ['node', ['field_upload'], 'field_media_document', ['article', 'blog', 'gleaning']],
    // new field would need to be added for generic file media (field_upload contains variety of file types)
  ];

  \Drupal::logger('geo_upgrade')->log(LogLevel::INFO, "Transformation started.");
  foreach ($transformations as $transformation) {
    [$entity_type, $image_field_names, $media_field_name, $bundles] = $transformation;

    /** @var \Drupal\migration_helpers\MigrationHelperFieldTransformations $field_transformations_service */
    $field_transformations_service = \Drupal::service('migration_helpers.field_transformations');
    $field_transformations_service->fieldToMediaEntity($entity_type, $image_field_names, $media_field_name, $bundles);

    $source_fields = implode(', ', $image_field_names);
    \Drupal::logger('geo_upgrade')->log(LogLevel::INFO, "Data in image field(s) $source_fields of $entity_type entity moved to $media_field_name media reference field.");
  }
}
