<?php

declare(strict_types=1);

namespace Drupal\ffmpeg_media_ui\Hook;

use Drupal\Core\Hook\Attribute\Hook;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Page attachment hooks for FFmpeg Media UI.
 */
final class PageAttachmentsHooks {

  /**
   * Routes that require the collapsible media tabs fallback.
   *
   * @var array<int, string>
   */
  private const array MEDIA_TAB_ROUTES = [
    'ffmpeg_media_ui.status',
    'ffmpeg_media_ui.transcode',
    'ffmpeg_media_ui.poster_select',
  ];

  /**
   * Constructs a new PageAttachmentsHooks instance.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $routeMatch
   *   The current route match.
   */
  public function __construct(
    protected readonly RouteMatchInterface $routeMatch,
  ) {}

  /**
   * Implements hook_page_attachments().
   *
   * @param array<string, mixed> &$attachments
   *   The page attachments render array.
   */
  #[Hook('page_attachments')]
  public function pageAttachments(array &$attachments): void {
    $routeName = $this->routeMatch->getRouteName();
    if ($routeName === NULL || !$this->isMediaTabsRoute($routeName)) {
      return;
    }

    $attachments['#attached']['library'] ??= [];
    if (!in_array('ffmpeg_media_ui/media-local-tasks', $attachments['#attached']['library'], TRUE)) {
      $attachments['#attached']['library'][] = 'ffmpeg_media_ui/media-local-tasks';
    }
  }

  /**
   * Determines whether the current route can render media local tasks.
   */
  private function isMediaTabsRoute(string $routeName): bool {
    if (str_starts_with($routeName, 'entity.media.')) {
      return TRUE;
    }

    return in_array($routeName, self::MEDIA_TAB_ROUTES, TRUE);
  }

}
