<?php

namespace Drupal\acquia_dam\EventSubscriber;

use Drupal\acquia_dam\Entity\ImageAltTextField;
use Drupal\acquia_dam\Plugin\media\Source\Asset;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Injects imageSourceMetadata into the CKEditor5 media metadata response.
 *
 * This is for DAM image media, enabling the core alt text / decorative image
 * command.
 */
class CKEditor5MediaMetadataSubscriber implements EventSubscriberInterface {

  public function __construct(
    private readonly EntityRepositoryInterface $entityRepository,
    private readonly RouteMatchInterface $routeMatch,
  ) {}

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    return [KernelEvents::RESPONSE => ['onResponse']];
  }

  /**
   * Adds imageSourceMetadata for DAM image media to the CKEditor5 metadata.
   */
  public function onResponse(ResponseEvent $event): void {
    // Only act on the CKEditor5 media metadata route.
    if ($this->routeMatch->getRouteName() !== 'ckeditor5.media_entity_metadata') {
      return;
    }

    $uuid = $event->getRequest()->query->get('uuid');
    if (!$uuid) {
      return;
    }

    $media = $this->entityRepository->loadEntityByUuid('media', $uuid);
    if (!$media) {
      return;
    }

    // Only inject for the DAM 'image' derivative — not video, audio, PDF, etc.
    $source = $media->getSource();
    if (!$source instanceof Asset || $source->getDerivativeId() !== 'image') {
      return;
    }

    // Provide the stored DAM alt text as the default so the CKEditor5 form
    // can show "Leave blank to use the default alternative text: <value>".
    $alt = '';
    if ($media->hasField(ImageAltTextField::IMAGE_ALT_TEXT_FIELD_NAME)) {
      $translated = $this->entityRepository->getTranslationFromContext($media);
      $alt = $translated->get(ImageAltTextField::IMAGE_ALT_TEXT_FIELD_NAME)->value ?? '';
    }

    // Inject imageSourceMetadata — the same structure core uses for standard
    // image media. This causes the core mediaImageTextAlternative command to
    // set drupalMediaIsImage = true, enabling the decorative image button.
    $response = $event->getResponse();
    $data = json_decode($response->getContent(), TRUE);
    $data['imageSourceMetadata'] = ['alt' => $alt];
    $response->setContent(json_encode($data));
  }

}
