<?php

namespace Drupal\acquia_contenthub_metatag\EventSubscriber\SerializeContentField;

use Drupal\acquia_contenthub\AcquiaContentHubEvents;
use Drupal\acquia_contenthub\Event\SerializeCdfEntityFieldEvent;
use Drupal\acquia_contenthub\EventSubscriber\SerializeContentField\ContentFieldMetadataTrait;
use Drupal\acquia_contenthub\EventSubscriber\SerializeContentField\FallbackFieldSerializer;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\metatag\MetatagManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Subscribes to entity field serialization to handle metatags values.
 */
class EntityMetatagsSerializer extends FallbackFieldSerializer implements EventSubscriberInterface {

  use ContentFieldMetadataTrait;

  /**
   * Config Factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected ConfigFactoryInterface $configFactory;

  /**
   * Metatag manager.
   *
   * @var \Drupal\metatag\MetatagManager
   */
  protected MetatagManager $metatagManager;

  /**
   * EntityMetatagsSerializer constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The configuration factory interface.
   * @param \Drupal\metatag\MetatagManager $metatag_manager
   *   Metatag manager.
   */
  public function __construct(ConfigFactoryInterface $config_factory, MetatagManager $metatag_manager) {
    $this->configFactory = $config_factory;
    $this->metatagManager = $metatag_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    $events[AcquiaContentHubEvents::SERIALIZE_CONTENT_ENTITY_FIELD][] =
      ['onSerializeContentField', 110];
    return $events;
  }

  /**
   * Extract entity url to update metatag values.
   *
   * @param \Drupal\acquia_contenthub\Event\SerializeCdfEntityFieldEvent $event
   *   The content entity field serialization event.
   *
   * @throws \Exception
   */
  public function onSerializeContentField(SerializeCdfEntityFieldEvent $event) {
    // Bail early if it isn't a metatag field.
    if ($event->getField()->getFieldDefinition()->getType() != 'metatag') {
      return;
    }

    $config = $this->configFactory->getEditable('acquia_contenthub_metatag.settings');
    if ($config->get('ach_metatag_node_url_do_not_transform')) {
      return;
    }

    parent::onSerializeContentField($event);
    $entity = $event->getEntity();

    $langcode = $entity->language()->getId();
    $metatag_field_data = $event->getFieldData();
    $field_value = $metatag_field_data['value'][$langcode]['value'] ?? FALSE;
    if (!$field_value) {
      return;
    }
    $publisher_node_url = $entity->toUrl()->setAbsolute()->toString();

    // @todo remove this condition when we support metatag 2 and above.
    $metatag_values = function_exists('metatag_data_decode') ? metatag_data_decode($field_value) : unserialize($field_value, ['allowed_classes' => []]);
    $metatags = $this->metatagManager->tagsFromEntityWithDefaults($entity);
    $metatag_values['canonical_url'] = str_replace('[node:url]', $publisher_node_url, $metatags['canonical_url']);
    $metatag_field_data['value'][$langcode]['value'] = serialize($metatag_values);
    $event->setFieldData($metatag_field_data);
    $event->stopPropagation();
  }

}
