<?php

namespace Drupal\acquia_contenthub_subscriber\Libs\PullSyndication;

use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Class ServiceQueueBatchHandler.
 *
 * Handles batch processing operations for Content Hub service queue items.
 * This class is responsible for managing Drupal's batch API integration,
 * chunking data, and providing batch callbacks.
 *
 * @internal
 * @package Drupal\acquia_contenthub_subscriber\Libs\PullSyndication
 */
class ServiceQueueBatchHandler {

  use StringTranslationTrait;

  public const BATCH_SIZE = 50;

  /**
   * Handles CH service queue items in batch.
   *
   * Builds the batch structure, sets batch process functions and the items.
   *
   * @param array $queue_items
   *   An array of queue items to process.
   */
  public function processQueueItemsInBatch(array $queue_items): void {
    $batch = [
      'title' => $this->t('Process ContentHub Service queue'),
      'operations' => [],
      'finished' => [static::class, 'batchFinished'],
    ];
    $chunks = array_chunk($queue_items, static::BATCH_SIZE);
    foreach ($chunks as $chunk) {
      $batch['operations'][] = [
        [static::class, 'batchProcess'],
        [$chunk],
      ];
    }

    batch_set($batch);
  }

  /**
   * Processes the batch.
   *
   * The batch worker will run through the queued items and process them.
   *
   * @param array $data
   *   The data to process.
   * @param array $context
   *   The batch context.
   */
  public static function batchProcess(array $data, array &$context): void {
    try {
      /** @var \Drupal\acquia_contenthub\Libs\ServiceQueue\ServiceQueueHandler $service_queue_handler */
      $service_queue_handler = \Drupal::service('acquia_contenthub.service_queue_handler');
      $service_queue_handler->processQueueItems($data);
    }
    catch (\Exception $exception) {
      $context['errors'][] = $exception->getMessage();
      $context['success'] = FALSE;
    }
  }

  /**
   * Batch finished callback.
   *
   * @param bool $success
   *   Whether the batch process succeeded or not.
   * @param array $result
   *   Holds results.
   * @param array $operations
   *   An array of operations.
   */
  public static function batchFinished(bool $success, array $result, array $operations): void {
    $messenger = \Drupal::messenger();
    if ($success) {
      $messenger->addMessage(new TranslatableMarkup('Successfully processed all items.'));
      return;
    }
    $error_operation = reset($operations);
    $messenger->addMessage(new TranslatableMarkup('An error occurred while processing @operation with arguments : @args', [
      '@operation' => $error_operation[0],
      '@args' => print_r($error_operation[0], TRUE),
    ]));
  }

}
