import { Injectable } from '@nestjs/common';
import { MonitorAlertEntity } from './monitor-alert.entity';

type NotifyResult = {
  attempted: boolean;
  status: string;
  message: string;
};

@Injectable()
export class MonitorAlertNotificationService {
  private readonly enabled =
    (process.env.MONITORING_ALERT_NOTIFY_ENABLED ?? 'true').trim() !== 'false';
  private readonly webhookUrl =
    process.env.MONITORING_ALERT_WEBHOOK_URL?.trim() ?? '';
  private readonly webhookType =
    (process.env.MONITORING_ALERT_WEBHOOK_TYPE?.trim() ??
      'generic') as 'generic' | 'dingtalk' | 'wecom' | 'feishu';
  private readonly minSeverity =
    (process.env.MONITORING_ALERT_NOTIFY_MIN_SEVERITY?.trim() ??
      'warning') as 'info' | 'warning' | 'major' | 'critical';

  async notifyAlert(alert: MonitorAlertEntity) {
    if (!this.enabled) {
      return { attempted: false, status: 'disabled', message: '通知已关闭' } satisfies NotifyResult;
    }
    if (!this.webhookUrl) {
      return { attempted: false, status: 'skipped', message: '未配置 MONITORING_ALERT_WEBHOOK_URL' } satisfies NotifyResult;
    }
    if (this.rank(alert.severity) < this.rank(this.minSeverity)) {
      return { attempted: false, status: 'skipped', message: `告警级别低于通知阈值 ${this.minSeverity}` } satisfies NotifyResult;
    }

    try {
      const payload = this.buildPayload(alert);
      const response = await fetch(this.webhookUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!response.ok) {
        const text = await response.text();
        return {
          attempted: true,
          status: 'failed',
          message: `Webhook ${response.status}: ${text.slice(0, 300)}`,
        } satisfies NotifyResult;
      }
      return { attempted: true, status: 'sent', message: 'Webhook 推送成功' } satisfies NotifyResult;
    } catch (error) {
      return {
        attempted: true,
        status: 'failed',
        message: error instanceof Error ? error.message : 'Webhook 推送失败',
      } satisfies NotifyResult;
    }
  }

  private buildPayload(alert: MonitorAlertEntity) {
    const title = `[SentAI告警][${alert.severity.toUpperCase()}] ${alert.title}`;
    const lines = [
      `服务标识: ${alert.serviceKey}`,
      `分类: ${alert.category}`,
      `级别: ${alert.severity}`,
      `状态: ${alert.status}`,
      `次数: ${alert.occurrenceCount}`,
      `摘要: ${alert.summary}`,
      `最近发现: ${alert.lastDetectedAt.toISOString()}`,
    ];
    if (this.webhookType === 'dingtalk') {
      return { msgtype: 'markdown', markdown: { title, text: `### ${title}\n${lines.map((item) => `- ${item}`).join('\n')}` } };
    }
    if (this.webhookType === 'wecom') {
      return { msgtype: 'markdown', markdown: { content: `**${title}**\n${lines.map((item) => `> ${item}`).join('\n')}` } };
    }
    if (this.webhookType === 'feishu') {
      return { msg_type: 'text', content: { text: `${title}\n${lines.join('\n')}` } };
    }
    return {
      source: 'sentai-monitoring',
      alert: {
        id: alert.id,
        title,
        serviceKey: alert.serviceKey,
        category: alert.category,
        severity: alert.severity,
        status: alert.status,
        occurrenceCount: alert.occurrenceCount,
        summary: alert.summary,
        lastDetectedAt: alert.lastDetectedAt.toISOString(),
      },
    };
  }

  private rank(value: 'info' | 'warning' | 'major' | 'critical') {
    return { info: 1, warning: 2, major: 3, critical: 4 }[value];
  }
}
