<?php

declare(strict_types=1);

namespace Drupal\flowdrop\Hook;

use Drupal\Core\Hook\Attribute\Hook;
use Drupal\Core\Routing\RouteProviderInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;
use Drupal\flowdrop\Constants\Permissions;

/**
 * FlowDrop hooks implementation.
 *
 * @internal This class is not part of the public API and may change without notice.
 */
final class FlowDropHooks {

  use StringTranslationTrait;

  /**
   * Constructs a new FlowDropHooks object.
   *
   * @param \Drupal\Core\Routing\RouteProviderInterface $routeProvider
   *   The route provider service.
   * @param \Drupal\Core\Session\AccountProxyInterface $currentUser
   *   The current user.
   */
  public function __construct(
    protected readonly RouteProviderInterface $routeProvider,
    protected readonly AccountProxyInterface $currentUser,
  ) {}

  /**
   * Implements hook_flowdrop_node_processor_info_alter().
   *
   * @param array<string, mixed> $data
   *   The processor info data.
   */
  #[Hook('flowdrop_node_processor_info_alter')]
  public function flowdropNodeProcessorInfoAlter(array &$data): void {}

  /**
   * Implements hook_toolbar().
   *
   * Adds a FlowDrop item to the admin toolbar for quick access.
   *
   * @return array<string, mixed>
   *   A render array for the toolbar item.
   */
  #[Hook('toolbar')]
  public function toolbar(): array {
    $items = [];

    // Check if the dashboard route exists.
    if (!$this->routeExists("flowdrop.dashboard")) {
      return $items;
    }

    $items["flowdrop"] = [
      "#type" => "toolbar_item",
      "#weight" => 50,
      "#access" => $this->currentUser->hasPermission(Permissions::ADMINISTER_FLOWDROP),
      "#cache" => [
        "contexts" => ["user.permissions"],
      ],
      "tab" => [
        "#type" => "link",
        "#title" => $this->t("FlowDrop"),
        "#url" => Url::fromRoute("flowdrop.dashboard"),
        "#attributes" => [
          "title" => $this->t("FlowDrop workflow automation"),
          "class" => ["toolbar-icon", "toolbar-icon-flowdrop"],
        ],
      ],
      "#attached" => [
        "library" => [
          "flowdrop/toolbar",
        ],
      ],
    ];

    return $items;
  }

  /**
   * Checks if a route exists.
   *
   * @param string $routeName
   *   The route name.
   *
   * @return bool
   *   TRUE if the route exists, FALSE otherwise.
   */
  protected function routeExists(string $routeName): bool {
    try {
      $this->routeProvider->getRouteByName($routeName);
      return TRUE;
    }
    catch (\Exception $e) {
      return FALSE;
    }
  }

}
