<?php

namespace Drupal\nodehive_api_key_management\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\TempStore\PrivateTempStoreFactory;
use Drupal\Core\Url;
use Drupal\nodehive_api_key_management\Service\ApiKeyManager;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Controller for listing API keys.
 */
class ApiKeyListController extends ControllerBase {

  /**
   * The API key manager service.
   *
   * @var \Drupal\nodehive_api_key_management\Service\ApiKeyManager
   */
  protected $apiKeyManager;

  /**
   * The private temp store factory.
   *
   * @var \Drupal\Core\TempStore\PrivateTempStoreFactory
   */
  protected $privateTempStoreFactory;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The date formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected $dateFormatter;

  /**
   * Constructs an ApiKeyListController object.
   */
  public function __construct(ApiKeyManager $api_key_manager, PrivateTempStoreFactory $private_temp_store_factory, EntityTypeManagerInterface $entity_type_manager, DateFormatterInterface $date_formatter) {
    $this->apiKeyManager = $api_key_manager;
    $this->privateTempStoreFactory = $private_temp_store_factory;
    $this->entityTypeManager = $entity_type_manager;
    $this->dateFormatter = $date_formatter;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('nodehive_api_key_management.api_key_manager'),
      $container->get('tempstore.private'),
      $container->get('entity_type.manager'),
      $container->get('date.formatter')
    );
  }

  /**
   * Lists all API keys.
   */
  public function listKeys() {
    $build = [];

    // Check if we just created a new key and need to display it.
    $tempstore = $this->privateTempStoreFactory->get('nodehive_api_key_management');
    $new_key = $tempstore->get('new_key');
    $new_key_id = $tempstore->get('new_key_id');

    if ($new_key && $new_key_id) {
      $build['new_key'] = [
        '#type' => 'container',
        '#attributes' => ['class' => ['messages', 'messages--warning']],
      ];

      $build['new_key']['title'] = [
        '#markup' => '<h3>' . $this->t('Your new API key') . '</h3>',
      ];

      $build['new_key']['message'] = [
        '#markup' => '<p>' . $this->t('Please copy this key now. You will not be able to see it again.') . '</p>',
      ];

      $build['new_key']['key'] = [
        '#type' => 'textarea',
        '#value' => $new_key,
        '#rows' => 2,
        '#attributes' => [
          'readonly' => 'readonly',
          'style' => 'font-family: monospace; width: 100%;',
        ],
      ];

      // Clear the tempstore.
      $tempstore->delete('new_key');
      $tempstore->delete('new_key_id');
    }

    // Load all keys.
    $keys = $this->apiKeyManager->loadAllKeys();

    if (empty($keys)) {
      $build['empty'] = [
        '#markup' => '<p>' . $this->t('No API keys have been created yet.') . '</p>',
      ];
      return $build;
    }

    // Build table.
    $header = [
      $this->t('Name'),
      $this->t('User'),
      $this->t('Prefix'),
      $this->t('Status'),
      $this->t('Rate Limit'),
      $this->t('Expiry'),
      $this->t('Last Used'),
      $this->t('Use Count'),
      $this->t('Operations'),
    ];

    $rows = [];
    foreach ($keys as $key) {
      $operations = [];

      if ($this->currentUser()->hasPermission('administer api keys')) {
        $operations['edit'] = [
          'title' => $this->t('Edit'),
          'url' => Url::fromRoute('nodehive_api_key_management.edit', ['key_id' => $key->id]),
        ];

        if ($key->status == 1) {
          $operations['revoke'] = [
            'title' => $this->t('Revoke'),
            'url' => Url::fromRoute('nodehive_api_key_management.revoke', ['key_id' => $key->id]),
          ];
        }

        $operations['delete'] = [
          'title' => $this->t('Delete'),
          'url' => Url::fromRoute('nodehive_api_key_management.delete', ['key_id' => $key->id]),
        ];
      }

      // Load user for display.
      $user = $this->entityTypeManager->getStorage('user')->load($key->uid);
      $user_display = $user ? $user->getDisplayName() : $this->t('Unknown (UID: @uid)', ['@uid' => $key->uid]);

      $rows[] = [
        $key->name,
        $user_display,
        ['data' => ['#markup' => '<code>' . $key->key_prefix . '</code>']],
        $key->status ? $this->t('Active') : $this->t('Revoked'),
        $key->rate_limit > 0 ? $this->t('@limit/hour', ['@limit' => $key->rate_limit]) : $this->t('Unlimited'),
        $key->expiry ? $this->t('@date', ['@date' => $this->dateFormatter->format($key->expiry, 'short')]) : $this->t('Never'),
        $key->last_used ? $this->t('@date', ['@date' => $this->dateFormatter->format($key->last_used, 'short')]) : $this->t('Never'),
        $key->use_count,
        [
          'data' => [
            '#type' => 'operations',
            '#links' => $operations,
          ],
        ],
      ];
    }

    $build['table'] = [
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#empty' => $this->t('No API keys available.'),
    ];

    return $build;
  }

}
