<?php

namespace Drupal\api_monitor_client\Alert\Handler;

use Drupal\api_monitor_client\Alert\AlertHandlerInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Mail\MailManager;
use Drupal\Core\Session\AccountProxyInterface;
use Psr\Log\LoggerInterface;

/**
 * Handles the sending of email alerts in response to specific API events.
 *
 * Implements AlertHandlerInterface.
 */
class EmailAlertHandler implements AlertHandlerInterface {

  /**
   * Constructor EmailAlertHandler.
   *
   * @param MailManager $mailManager
   *   Manages the sending of emails.
   * @param ConfigFactoryInterface $configFactory
   *   Provides configuration factory services.
   * @param LoggerInterface $logger
   *   Logs application messages.
   * @param AccountProxyInterface $accountProxy
   *   Proxy service for the current user account.
   */
  public function __construct(
    protected MailManager $mailManager,
    protected ConfigFactoryInterface $configFactory,
    private readonly LoggerInterface $logger,
    private readonly AccountProxyInterface $accountProxy,
  ) {}

  /**
   * Sends an alert email based on API status.
   *
   * @param string $api_id
   *   The identifier of the API being monitored.
   * @param string $type
   *   The type of alert being sent.
   * @param array $data
   *   Additional data to include in the alert email.
   *
   * @return void
   */
  public function sendAlert($api_id, $type, array $data) {
    $to = $this->configFactory->get('api_monitor_client.settings')->get('alert_email');
    if (empty($to)) {
      // Fallback email address.
      $to = $this->configFactory->get('system.site')->get('mail');
    }

    $langcode = $this->accountProxy->getPreferredLangcode();

    $params = array_merge($data, [
      'api_id' => $api_id,
      'type' => $type,
    ]);

    $result = $this->mailManager->mail(
      'api_monitor_client',
      'api_status_alert',
      $to,
      $langcode,
      $params,
      NULL,
      TRUE
    );

    $this->logger->info("Email di alert inviata a @to", ['@to' => $to]);

    if ($result['result'] !== TRUE) {
      $this->logger->error("Impossibile inviare l'email di alert a @to", ['@to' => $to]);
    }

  }

  /**
   * Checks if the email alerts are enabled.
   *
   * @return bool
   *   True if email alerts are active, false otherwise.
   */
  public function isEnabled() {
    return (bool) $this->configFactory->get('api_monitor_client.settings')->get('email_alerts_active');
  }

}
