<?php

namespace Drupal\acquia_contenthub_subscriber\EventSubscriber\HandleWebhook;

use Acquia\ContentHubClient\Settings;
use Drupal\acquia_contenthub\AcquiaContentHubEvents;
use Drupal\acquia_contenthub\Event\HandleWebhookEvent;
use Drupal\acquia_contenthub_subscriber\EntityDeletionHandlerBase;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Deletes assets based on a webhook.
 *
 * @package Drupal\acquia_contenthub_subscriber\EventSubscriber\HandleWebhook
 */
class DeleteAssets extends EntityDeletionHandlerBase implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    $events[AcquiaContentHubEvents::HANDLE_WEBHOOK][] = 'onHandleWebhook';
    return $events;
  }

  /**
   * Handles webhook events.
   *
   * @param \Drupal\acquia_contenthub\Event\HandleWebhookEvent $event
   *   The HandleWebhookEvent object.
   *
   * @throws \Exception
   */
  public function onHandleWebhook(HandleWebhookEvent $event): void {
    $payload = $event->getPayload();
    $assets = $payload['assets'] ?? [];
    $client = $event->getClient();
    $settings = $client->getSettings();

    if ($event->isWebhookV2() || !$this->isValidRequestPayload($payload, $settings)) {
      return;
    }

    $entity_uuids = [];
    $entity_uuids_to_cleanup = [];
    foreach ($assets as $asset) {
      if (!$this->isSupportedType($asset['type'])) {
        continue;
      }
      $entity_uuids[] = $asset['uuid'];
    }

    $this->processMultipleEntityDeletions($entity_uuids, $entity_uuids_to_cleanup);
    $this->cleanupMissingEntities($entity_uuids_to_cleanup, $client);
  }

  /**
   * Validates request payload.
   *
   * A valid payload should be successful, an event about deletion, and cannot
   * come from the same origin.
   *
   * @param array $payload
   *   The payload to validate.
   * @param \Acquia\ContentHubClient\Settings $settings
   *   The Content Hub settings.
   *
   * @return bool
   *   True if the payload is applicable.
   */
  protected function isValidRequestPayload(array $payload, Settings $settings): bool {
    $assets = $payload['assets'] ?? [];
    $client_uuid = $settings->getUuid();
    if (!isset($payload['status'], $payload['crud'], $payload['initiator'])) {
      return FALSE;
    }

    return 'successful' === $payload['status'] &&
      'delete' === $payload['crud'] &&
      $payload['initiator'] !== $client_uuid &&
      !empty($assets);
  }

}
