<?php

namespace Drupal\castorcito\Plugin\rest\resource;

use Drupal\castorcito\CastorcitoManager;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Provides a Castorcito Block list resource.
 *
 * @RestResource (
 *   id = "castorcito_block_list_resource",
 *   label = @Translation("Castorcito Block List Resource"),
 *   uri_paths = {
 *     "canonical" = "/api/castorcito-block-list"
 *   }
 * )
 */
class CastorcitoBlockListResource extends ResourceBase {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * The castorcito manager service.
   *
   * @var Drupal\castorcito\CastorcitoManager
   */
  protected $castorcitoManager;

  /**
   * Constructs a new BlockListResource object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   The current user service.
   * @param Drupal\castorcito\CastorcitoManager $castorcito_manager
   *   The castorcito manager.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user,
    CastorcitoManager $castorcito_manager,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
    $this->currentUser = $current_user;
    $this->castorcitoManager = $castorcito_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): self {
    return new self(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('current_user'),
      $container->get('castorcito.manager')
    );
  }

  /**
   * Responds to entity GET requests.
   *
   * @return \Drupal\rest\ModifiedResourceResponse
   *   A ModifiedResourceResponse object with the entity data.
   */
  public function get(Request $request) {
    $params = $request->query->all();

    if (empty($params['provider'])) {
      return new ResourceResponse(['message' => 'Missing required parameters: provider'], 400);
    }

    $provider = json_decode($params['provider'], TRUE);
    if (json_last_error() !== JSON_ERROR_NONE) {
      return new ResourceResponse(['message' => 'Invalid JSON format for provider.'], 400);
    }

    $definitions = $this->castorcitoManager->getBlockDefinitions();

    if (!empty($definitions)) {
      $filtered_data = [];

      foreach ($definitions as $key => $item) {
        if (in_array($item['provider'], $provider)) {
          $filtered_data[$key] = $item['admin_label'];
        }
      }

      // Add cache tags.
      $cache_metadata = new CacheableMetadata();
      $cache_metadata->addCacheTags(['block_content_list']);

      // Attach the cache metadata to the response.
      $response = new ResourceResponse($filtered_data, 200);
      $response->addCacheableDependency($cache_metadata);

      return $response;
    }
    else {
      return new ResourceResponse(['message' => 'No block definitions found'], 404);
    }
  }

}
