import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

export type AlertLevel = 'info' | 'warning' | 'critical';

export interface Alert {
  level: AlertLevel;
  /** Short human-readable subject */
  title: string;
  /** Multi-line detail; goes into the alert payload body. */
  body: string;
  /** Optional structured context for downstream filtering/grouping */
  context?: Record<string, unknown>;
}

/**
 * Operational alerter. Today: structured logger output (still visible in
 * stdout / log aggregator). Tomorrow: POST to a webhook (wecom / dingtalk /
 * slack / pagerduty) controlled by env `ALERT_WEBHOOK_URL`.
 *
 * Single seam — every place that needs to alert depends on this service,
 * not on the transport.
 */
@Injectable()
export class AlertService {
  private readonly logger = new Logger(AlertService.name);

  constructor(private readonly config: ConfigService) {}

  async send(alert: Alert): Promise<void> {
    const webhookUrl = this.config.get<string>('alert.webhookUrl') ?? '';
    const line = `[ALERT ${alert.level.toUpperCase()}] ${alert.title}\n${alert.body}`;

    if (alert.level === 'critical') this.logger.error(line);
    else if (alert.level === 'warning') this.logger.warn(line);
    else this.logger.log(line);

    if (webhookUrl) {
      try {
        await fetch(webhookUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            level: alert.level,
            title: alert.title,
            body: alert.body,
            context: alert.context,
            timestamp: new Date().toISOString(),
          }),
          signal: AbortSignal.timeout(5_000),
        });
      } catch (err) {
        this.logger.error(
          `Failed to deliver alert webhook: ${err instanceof Error ? err.message : String(err)}`,
        );
      }
    }
  }
}
