<?php

declare(strict_types=1);

namespace Drupal\native_observability\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\native_observability\Service\RequestLogExclusionRepository;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Lists request-log exclusion rules.
 */
final class RequestLogExclusionListController extends ControllerBase {

  public function __construct(
    private readonly RequestLogExclusionRepository $repository,
  ) {
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): self {
    return new self(
      $container->get('native_observability.request_log_exclusion_repository'),
    );
  }

  /**
   * Builds the admin listing page.
   */
  public function listing(): array {
    $header = [
      $this->t('Label'),
      $this->t('Status'),
      $this->t('Method'),
      $this->t('Path match'),
      $this->t('Conditions'),
      $this->t('Operations'),
    ];

    $rows = [];
    foreach ($this->repository->loadAll() as $rule) {
      $id = (int) ($rule['id'] ?? 0);
      $operations = [
        Link::fromTextAndUrl($this->t('Edit'), Url::fromRoute('native_observability.request_log_exclusion_edit', ['id' => $id]))->toString(),
        Link::fromTextAndUrl($this->t('Delete'), Url::fromRoute('native_observability.request_log_exclusion_delete', ['id' => $id]))->toString(),
      ];

      $rows[] = [
        (string) ($rule['label'] ?? ''),
        !empty($rule['enabled']) ? $this->t('Enabled') : $this->t('Disabled'),
        (string) ($rule['method'] ?? 'ANY'),
        sprintf('%s: %s', (string) ($rule['path_match_type'] ?? 'exact'), (string) ($rule['path_pattern'] ?? '')),
        $this->formatPlural(
          count(json_decode((string) ($rule['query_conditions'] ?? '[]'), TRUE) ?: []),
          '1 condition',
          '@count conditions',
        ),
        [
          'data' => [
            '#markup' => implode(' | ', $operations),
          ],
        ],
      ];
    }

    return [
      'actions' => [
        '#type' => 'link',
        '#title' => $this->t('Add exclusion rule'),
        '#url' => Url::fromRoute('native_observability.request_log_exclusion_add'),
        '#attributes' => ['class' => ['button', 'button--primary']],
      ],
      'table' => [
        '#type' => 'table',
        '#header' => $header,
        '#rows' => $rows,
        '#empty' => $this->t('No exclusion rules defined yet.'),
      ],
    ];
  }

}
