<?php

declare(strict_types=1);

namespace Drupal\api_monitor_client\Hook;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Hook\Attribute\Hook;
use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
 * Hook implementations for the Mail system.
 */
final class MailHooks {
  use StringTranslationTrait;

  /**
   * Construct MailHooks.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
   *   The config factory.
   */
  public function __construct(
    protected readonly ConfigFactoryInterface $configFactory,
  ) {
  }

  /**
   * Implements hook_mail().
   */
  #[Hook('mail')]
  public function mail($key, &$message, $params): void {
    if ($key !== 'api_status_alert') {
      return;
    }

    $message['from'] = $this->configFactory->get('system.site')->get('mail');
    $message['subject'] = $this->t('ALERT API: @api_id - @type', [
      '@api_id' => $params['api_id'],
      '@type' => $params['type'],
    ]);

    $message['body'][] = $this->t("Rilevato problema sull\'API: @id", ['@id' => $params['api_id']]);
    $message['body'][] = $this->t('Tipo Alert: @type', ['@type' => $params['type']]);

    if (isset($params['uptime'])) {
      $message['body'][] = $this->t('Uptime attuale: @uptime%', ['@uptime' => $params['uptime']]);
    }

    if (isset($params['code'])) {
      $message['body'][] = $this->t('Ultimo Status Code: @code', ['@code' => $params['code']]);
    }

    if ($params['type'] === 'AI_CRITICAL_ALERT') {
      $message['body'][] = $this->t('--- ANALISI AI ---');
      $message['body'][] = $this->t('Sommario: @summary', ['@summary' => $params['summary'] ?? 'N/A']);
      if (!empty($params['issues'])) {
        $message['body'][] = $this->t('Problemi riscontrati:');
        foreach ($params['issues'] as $issue) {
          $message['body'][] = "- $issue";
        }
      }
    }

    $message['body'][] = $this->t('Controlla la dashboard per maggiori dettagli.');
  }

}
