<?php

declare(strict_types=1);

namespace Drupal\nodehive_content_browser\Controller;

use Drupal\Core\Url;
use Drupal\Core\Controller\ControllerBase;
use Drupal\nodehive_content_browser\Service\ContentSearchService;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Controller for content browser functionality.
 */
class ContentBrowserController extends ControllerBase {

  /**
   * The content search service.
   *
   * @var \Drupal\nodehive_content_browser\Service\ContentSearchService
   */
  protected $contentSearchService;

  /**
   * Constructs a ContentBrowserController object.
   *
   * @param \Drupal\nodehive_content_browser\Service\ContentSearchService $content_search_service
   *   The content search service.
   */
  public function __construct(ContentSearchService $content_search_service) {
    $this->contentSearchService = $content_search_service;
  }

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

  /**
   * Returns available content types for creation.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   JSON response with content types.
   */
  public function contentTypes(): JsonResponse {
    $types = [];
    $node_types = $this->entityTypeManager()->getStorage('node_type')->loadMultiple();

    foreach ($node_types as $type) {
      // Check if user has permission to create this content type.
      if ($this->currentUser()->hasPermission('create ' . $type->id() . ' content')) {
        $types[] = [
          'id' => $type->id(),
          'label' => $type->label(),
          'description' => $type->getDescription(),
          'create_url' => Url::fromRoute('node.add', ['node_type' => $type->id()])->toString(),
        ];
      }
    }

    return new JsonResponse(['content_types' => $types]);
  }

  /**
   * Handles content search requests.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   JSON response with search results.
   */
  public function search(Request $request): JsonResponse {
    $query = $request->query->get('q', '');
    $limit = (int) $request->query->get('limit', 20);
    $offset = (int) $request->query->get('offset', 0);

    // Perform search.
    $results = $this->contentSearchService->search($query, $limit, $offset);

    return new JsonResponse($results);
  }

}
