<?php

namespace Drupal\acquia_contenthub_publisher\EventSubscriber\HandleWebhook;

use Drupal\acquia_contenthub\AcquiaContentHubEvents;
use Drupal\acquia_contenthub\Event\HandleWebhookEvent;
use Drupal\acquia_contenthub_publisher\PublisherTracker;
use Drupal\Core\Database\Connection;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class UpdateMultiplePublishedAssets.
 *
 * Subscribes to onHandleWebhook.
 */
class UpdateMultiplePublishedAssets implements EventSubscriberInterface {

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected Connection $database;

  /**
   * UpdatePublished constructor.
   *
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection.
   */
  public function __construct(Connection $database) {
    $this->database = $database;
  }

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

  /**
   * On handle webhook event.
   *
   * @param \Drupal\acquia_contenthub\Event\HandleWebhookEvent $event
   *   The handle webhook event.
   */
  public function onHandleWebhook(HandleWebhookEvent $event) {
    $payload = $event->getPayload();
    $client = $event->getClient();
    if ($this->shouldSkipWebhookHandling($payload, $event->isWebhookV2())) {
      return;
    }
    $uuids = [];
    foreach ($payload['assets'] as $asset) {
      if ($this->shouldSkipAsset($asset, $client->getSettings()->getUuid())) {
        continue;
      }
      $uuids[] = $asset['uuid'];
    }
    if (empty($uuids)) {
      return;
    }
    $query = $this->database->select('acquia_contenthub_publisher_export_tracking', 'acpet')
      ->fields('acpet', ['entity_uuid']);
    $query->condition('acpet.entity_uuid', $uuids, 'IN');
    $items = $query->execute()->fetchAll();
    $uuids = [];
    foreach ($items as $item) {
      $uuids[] = $item->entity_uuid;
    }
    $update = $this->database->update('acquia_contenthub_publisher_export_tracking')
      ->fields(['status' => PublisherTracker::CONFIRMED]);
    $update->condition('entity_uuid', $uuids, 'IN');
    $update->execute();
  }

  /**
   * Checks if webhook handling should be skipped.
   *
   * @param array $payload
   *   Payload.
   * @param bool $is_webhook_v2
   *   True if webhook is V2, otherwise False.
   *
   * @return bool
   *   True if webhook handling to be skipped, otherwise False.
   */
  protected function shouldSkipWebhookHandling(array $payload, bool $is_webhook_v2): bool {
    return !$is_webhook_v2 ||
      empty($payload['assets']) ||
      $payload['status'] !== 'successful' ||
      $payload['crud'] !== 'update';
  }

  /**
   * Checks if payload asset to be skipped.
   *
   * @param array $asset
   *   Payload asset.
   * @param string $client_uuid
   *   Client uuid.
   *
   * @return bool
   *   True if asset to be skipped, otherwise False.
   */
  protected function shouldSkipAsset(array $asset, string $client_uuid): bool {
    $allowed_types = ['drupal8_content_entity', 'drupal8_config_entity'];
    return (!in_array($asset['type'], $allowed_types) ||
      empty($asset['origin']) || $asset['origin'] !== $client_uuid);
  }

}
