<?php

declare(strict_types=1);

namespace Drupal\lrs_xapi\EventSubscriber;

use Drupal\Component\EventDispatcher\Event;
use Drupal\lrs_xapi\XapiStatementStorage;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Xapi LRS event subscriber.
 */
final class LrsXapiSubscriber implements EventSubscriberInterface {

  /**
   * Constructor.
   */
  public function __construct(
    private readonly XapiStatementStorage $statementStorage,
  ) {}

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    return ['xapi_reference_operation' => [['onReferenceOperation', 100]]];
  }

  /**
   * Act on Xapi reference operation.
   */
  public function onReferenceOperation(Event $event): void {
    // Avoid hard dependency.
    if (
      !\class_exists('Drupal\lms_xapi\Event\ReferenceEvent') ||
      \get_class($event) !== 'Drupal\lms_xapi\Event\ReferenceEvent'
    ) {
      return;
    }

    // @todo Allow not deleting statements in config for
    // Xapi standard compliance.
    if ($event->getOperation() === 'delete') {
      $registration_ids = $event->getRegistrationIds();
      if (\count($registration_ids) === 0) {
        return;
      }
      $this->statementStorage->deleteByRegistrationIds($registration_ids);
    }
  }

}
