<?php

namespace Drupal\jsonapi_query_builder\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Controller for the JSON:API Query Builder.
 */
class ExplorerController extends ControllerBase {

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * Constructs a new ExplorerController object.
   *
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
   */
  public function __construct(ModuleHandlerInterface $module_handler) {
    $this->moduleHandler = $module_handler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): static {
    return new static(
      $container->get('module_handler')
    );
  }

  /**
   * Displays the JSON:API Query Builder app.
   *
   * @return array
   *   Render array for the explorer application.
   */
  public function explorer(): array {
    $jsonapi_url = Url::fromRoute('jsonapi.resource_list', [], ['absolute' => TRUE])->toString();

    return [
      '#theme' => 'jsonapi_query_builder',
      '#base_url' => $jsonapi_url,
      '#attached' => [
        'library' => ['jsonapi_query_builder/query_builder'],
        'drupalSettings' => [
          'jsonapi_query_builder' => [
            'baseUrl' => $jsonapi_url,
          ],
        ],
      ],
    ];
  }

}
