<?php

namespace Drupal\acquia_contenthub\Commands;

use Drupal\acquia_contenthub\ContentHubCommonActions;
use Drupal\Component\Uuid\Uuid;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Serialization\Yaml;
use Drush\Commands\DrushCommands;

/**
 * Class AcquiaContentHubCommands.
 *
 * @package Drupal\acquia_contenthub\Commands
 */
class AcquiaContentHubCDFCommands extends DrushCommands {

  /**
   * The common actions object.
   *
   * @var \Drupal\acquia_contenthub\ContentHubCommonActions
   */
  protected ContentHubCommonActions $common;

  /**
   * The entity repository service.
   *
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
   */
  protected EntityRepositoryInterface $entityRepository;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected EntityTypeManagerInterface $entityTypeManager;

  /**
   * AcquiaContentHubCDFCommands constructor.
   *
   * @param \Drupal\acquia_contenthub\ContentHubCommonActions $common
   *   The common actions object.
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   The Entity Repository service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(ContentHubCommonActions $common, EntityRepositoryInterface $entity_repository, EntityTypeManagerInterface $entity_type_manager) {
    $this->common = $common;
    $this->entityRepository = $entity_repository;
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * Generates a CDF Document from a manifest file.
   *
   * @todo move this command to publisher in export optimization/refactor.
   *
   * @param string $manifest
   *   The location of the manifest file.
   *
   * @command acquia:contenthub-export-local-cdf
   * @aliases ach-elc
   *
   * @return false|string
   *   The json output if successful or false.
   *
   * @throws \Exception
   */
  public function exportCdf($manifest) {
    if (!file_exists($manifest)) {
      throw new \Exception("The provided manifest file does not exist in the specified location.");
    }
    $manifest = Yaml::decode(file_get_contents($manifest));
    $entities = [];
    foreach ($manifest['entities'] as $entity) {
      [$entity_type_id, $entity_id] = explode(":", $entity);
      if (!Uuid::isValid($entity_id)) {
        $entities[] = $this->entityTypeManager->getStorage($entity_type_id)->load($entity_id);
        continue;
      }
      $entities[] = $this->entityRepository->loadEntityByUuid($entity_type_id, $entity_id);
    }
    if (!$entities) {
      throw new \Exception("No entities loaded from the manifest.");
    }
    return $this->common->getLocalCdfDocument(...$entities)->toString();
  }

}
