<?php

declare(strict_types=1);

namespace Drupal\lms_xapi_lesson;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\lms\Entity\Bundle\Course;
use Drupal\lms\TrainingManager;
use Drupal\lms_xapi\XapiIdGeneratorInterface;
use Drupal\lms_xapi_lesson\Entity\Bundle\XapiLesson;

/**
 * Xapi LRS event subscriber.
 */
final class LessonXapiIdGenerator implements XapiIdGeneratorInterface {

  /**
   * Constructor.
   */
  public function __construct(
    private readonly RouteMatchInterface $routeMatch,
    private readonly TrainingManager $trainingManager,
  ) {}

  /**
   * {@inheritdoc}
   */
  public function applies(
    EntityInterface $entity,
    AccountInterface $student,
    CacheableMetadata $cacheable_metadata,
  ): bool {
    if (!$entity instanceof XapiLesson) {
      return FALSE;
    }
    $course = $this->routeMatch->getParameter('group');
    $cacheable_metadata->setCacheContexts($cacheable_metadata->getCacheContexts() + ['route']);
    if ($course instanceof Course) {
      $course_status = $this->trainingManager->loadCourseStatus($course, $student, [
        'current' => TRUE,
      ]);
      $cacheable_metadata->addCacheableDependency($course_status);
      return $course_status !== NULL;
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function generate(
    EntityInterface $entity,
    AccountInterface $student,
    CacheableMetadata $cacheable_metadata,
  ): array {

    $course = $this->routeMatch->getParameter('group');
    $course_status = $this->trainingManager->loadCourseStatus($course, $student, [
      'current' => TRUE,
    ]);

    return [
      $entity->getEntityTypeId(),
      $entity->id(),
      $course_status->id(),
    ];
  }

}
