<?php

namespace Drupal\acquia_contenthub\EventSubscriber\HandleWebhook;

use Drupal\acquia_contenthub\AcquiaContentHubEvents;
use Drupal\acquia_contenthub\Event\HandleWebhookEvent;
use Drupal\acquia_contenthub\Settings\ContentHubConfigurationInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Handles webhook with a payload to regenerate shared secret.
 *
 * And save it in config.
 *
 * @package Drupal\acquia_contenthub\EventSubscriber\HandleWebhook
 */
class RegenerateSharedSecret implements EventSubscriberInterface {

  /**
   * Webhook's regenerate shared secret crud.
   */
  public const CRUD = 'regenerate';

  /**
   * CH configurations.
   *
   * @var \Drupal\acquia_contenthub\Settings\ContentHubConfigurationInterface
   */
  protected ContentHubConfigurationInterface $achConfigurations;

  /**
   * Content Hub Logger Channel.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

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

  /**
   * RegenerateSharedSecret constructor.
   *
   * @param \Drupal\acquia_contenthub\Settings\ContentHubConfigurationInterface $ch_configuration
   *   Content Hub config.
   * @param \Psr\Log\LoggerInterface $logger
   *   Content Hub logger channel.
   */
  public function __construct(ContentHubConfigurationInterface $ch_configuration, LoggerInterface $logger) {
    $this->achConfigurations = $ch_configuration;
    $this->logger = $logger;
  }

  /**
   * On handle webhook event.
   *
   * @param \Drupal\acquia_contenthub\Event\HandleWebhookEvent $event
   *   The handle webhook event.
   */
  public function onHandleWebhook(HandleWebhookEvent $event): void {
    $payload = $event->getPayload();
    if (empty($payload['crud']) || self::CRUD !== $payload['crud']) {
      return;
    }
    $shared_secret = $payload['message'] ?? '';
    if (empty($shared_secret)) {
      $this->logger->error('Regenerated shared secret not found in the payload.');
      return;
    }

    $this->achConfigurations->getConnectionDetails()->setSharedSecret($shared_secret);
    $this->logger->info('Regenerated shared secret has been updated in Content Hub settings config successfully.');
  }

}
