<?php

namespace Drupal\api_monitor_client\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Controller for the API detail page.
 */
class ApiDetailController extends ControllerBase {

  /**
   * Constructor ApiDetailController.
   *
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   */
  public function __construct(
    protected readonly Connection $database,
    private readonly LoggerInterface $logger,
  ) {
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('database'),
      $container->get('logger.channel.api_monitor_client')
    );
  }

  /**
   * Builds the API detail page.
   *
   * @param string $api_id
   *   The endpoint ID.
   *
   * @return array
   *   Render array.
   */
  public function build(string $api_id) {
    try {
      // Retrieve information for charts.
      $window = time() - (72 * 3600);
      $query = $this->database->select('api_monitor_history', 'h')
        ->fields('h', ['timestamp', 'response_time', 'success', 'status_code'])
        ->condition('api_id', $api_id)
        ->condition('timestamp', $window, '>=')
        ->orderBy('timestamp');

      $results = $query->execute()->fetchAll();
    }
    catch (\Throwable $e) {
      $this->logger->error($e->getMessage());
      return [];
    }

    $labels = [];
    $response_times = [];
    $success_count = 0;
    $total_count = count($results);
    $sum_latencies = 0;

    foreach ($results as $row) {
      $labels[] = date('H:i', $row->timestamp);
      $response_times[] = $row->response_time;
      if($row->success) $success_count++;
      $sum_latencies += $row->response_time;
    }

    // Calc Medie e Uptime.
    $uptime_percentage = $total_count > 0 ? round(($success_count / $total_count) * 100, 2) : 0;
    $avg_latency = $total_count > 0 ? round($sum_latencies / $total_count, 2) : 0;

    return [
      '#theme' => 'api_monitor_detail',
      '#api_id' => $api_id,
      '#uptime' => $uptime_percentage,
      '#avg_latency' => $avg_latency,
      '#total_checks' => $total_count,
      '#attached' => [
        'library' => ['api_monitor_client/api_charts'],
        'drupalSettings' => [
          'apiMonitorData' => [
            'labels' => $labels,
            'values' => $response_times,
            'label_text' => $this->t('Latenza (ms)'),
          ],
        ],
      ],
    ];
  }

}
