<?php

declare(strict_types=1);

namespace Drupal\ffmpeg_media_ui\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\ffmpeg_media\Service\FormatterSettingsResolverInterface;
use Drupal\media\MediaInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Route access callback ensuring FFmpeg formatter configuration exists.
 */
final class MediaMappingAccess implements ContainerInjectionInterface {

  /**
   * Constructs a MediaMappingAccess object.
   *
   * @param \Drupal\ffmpeg_media\Service\FormatterSettingsResolverInterface $formatterSettingsResolver
   *   Formatter settings resolver service.
   */
  public function __construct(
    protected readonly FormatterSettingsResolverInterface $formatterSettingsResolver,
  ) {}

  /**
   * {@inheritdoc}
   */
  #[\Override]
  public static function create(ContainerInterface $container): static {
    return new static(
      $container->get(FormatterSettingsResolverInterface::class),
    );
  }

  /**
   * Grants access only when a formatter configuration exists for the bundle.
   *
   * @param \Drupal\media\MediaInterface $media
   *   The media route parameter.
   *
   * @return \Drupal\Core\Access\AccessResult
   *   Access decision with proper cacheability metadata.
   */
  public function access(MediaInterface $media): AccessResult {
    $hasMapping = $this->formatterSettingsResolver->getContextsForEntity($media) !== [];

    return AccessResult::allowedIf($hasMapping)
      ->addCacheableDependency($media)
      ->addCacheTags(['config:core.entity_view_display.media.' . $media->bundle() . '.default']);
  }

}
