<?php

namespace Drupal\api_monitor_client\Alert;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\State\StateInterface;

/**
 * Manage the alerting system.
 */
class AlertManager {

  /**
   * Construct AlertManager.
   *
   * @param \Drupal\Core\State\StateInterface $state
   *   The state service.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
   *   The config factory.
   * @param array $handlers
   *   List of handlers.
   */
  public function __construct(
    private readonly StateInterface $state,
    private readonly ConfigFactoryInterface $configFactory,
    protected array $handlers = [],
  ) {
  }

  /**
   * Add a handler to the alerting system, called in services container.
   *
   * @param \Drupal\api_monitor_client\Alert\AlertHandlerInterface $handler
   *   The handler to add.
   *
   * @return void
   */
  public function addHandler(AlertHandlerInterface $handler) {
    $this->handlers[] = $handler;
  }

  /**
   * Sends a notification through enabled handlers.
   *
   * @param string $api_id
   *   The unique identifier of the API.
   * @param string $type
   *   The type of notification to send.
   * @param array $data
   *   The data associated with the notification.
   *
   * @return void
   */
  public function notify($api_id, $type, array $data) {
    if (!$this->shouldSend($api_id, $type)) {
      return;
    }

    foreach ($this->handlers as $handler) {
      if ($handler->isEnabled()) {
        $handler->sendAlert($api_id, $type, $data);
      }
    }

    $this->state->set("api_monitor.last_alert.$api_id.$type", time());
  }

  /**
   * Determines whether an alert should be sent based on the resend interval.
   *
   * @param string $api_id
   *   The ID of the API.
   * @param string $type
   *   The type of alert.
   *
   * @return bool
   *   TRUE if the alert should be sent, FALSE otherwise.
   */
  private function shouldSend($api_id, $type) {
    $config = $this->configFactory->get('api_monitor_client.settings');
    $interval_minutes = $config->get('resend_interval') ?: 60;
    $interval_seconds = $interval_minutes * 60;

    $last_sent = $this->state->get("api_monitor.last_alert.$api_id.$type", 0);

    return (time() - $last_sent) > $interval_seconds;
  }

}
