<?php

namespace Drupal\acquia_dam\Plugin\views\filter;

use Drupal\acquia_dam\Client\AcquiaDamClientFactory;
use Drupal\Core\Logger\LoggerChannelInterface;
use Drupal\views\Plugin\views\filter\InOperator;
use Drupal\views_remote_data\Plugin\views\query\RemoteDataQuery;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Filter for assets based on collections.
 *
 * @ViewsFilter("acquia_dam_collection_filter")
 */
class CollectionFilter extends InOperator {

  /**
   * DAM client factory.
   *
   * @var \Drupal\acquia_dam\Client\AcquiaDamClientFactory
   */
  protected $damClientFactory;

  /**
   * Logger channel.
   *
   * @var \Drupal\Core\Logger\LoggerChannelInterface
   */
  protected $logger;

  /**
   * Constructs a CollectionFilter object.
   *
   * @param array $configuration
   *   Configuration array.
   * @param string $plugin_id
   *   Plugin ID.
   * @param mixed $plugin_definition
   *   Plugin definition.
   * @param \Drupal\acquia_dam\Client\AcquiaDamClientFactory $damClientFactory
   *   DAM Client Factory.
   * @param \Drupal\Core\Logger\LoggerChannelInterface $logger
   *   Logger channel for acquia_dam.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, AcquiaDamClientFactory $damClientFactory, LoggerChannelInterface $logger) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->damClientFactory = $damClientFactory;
    $this->logger = $logger;
    $this->valueFormType = 'select';
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('acquia_dam.client.factory'),
      $container->get('logger.channel.acquia_dam')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getValueOptions(): array {
    $this->valueOptions = [];

    try {
      $client = $this->damClientFactory->getUserClient();
      $collections = $client->getCollections();

      foreach ($collections['items'] ?? [] as $collection) {
        $this->valueOptions[$collection['title']] = $collection['title'];
      }
    }
    catch (\Exception $e) {
      // Use injected logger for error reporting.
      $this->logger->error('Failed to fetch collections for filter options: @message', [
        '@message' => $e->getMessage(),
      ]);
    }

    return $this->valueOptions;
  }

  /**
   * {@inheritdoc}
   */
  public function query() {
    assert($this->query instanceof RemoteDataQuery);

    if (!empty($this->value)) {
      // Build the collection filter for Widen API.
      $collection_query = 'acn:(' . implode(' OR ', $this->value) . ')';

      $this->query->addWhere(
        $this->options['group'],
        'query',
        $collection_query,
        $this->operator
      );
    }
  }

}
