package com.davos.assessment.common;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class OpsMonitorJob {
  private final JdbcTemplate jdbcTemplate;
  private final String webhook;
  private final HttpClient httpClient;

  public OpsMonitorJob(
      JdbcTemplate jdbcTemplate,
      @Value("${app.alert.webhook-url:}") String webhook) {
    this.jdbcTemplate = jdbcTemplate;
    this.webhook = webhook == null ? "" : webhook.trim();
    this.httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
  }

  @Scheduled(cron = "${app.alert.db-check-cron:0 */5 * * * *}")
  public void dbHealthCheck() {
    try {
      Integer ok = jdbcTemplate.queryForObject("select 1", Integer.class);
      if (ok == null || ok != 1) {
        notifyWebhook("DB_HEALTH_CHECK", "数据库健康检查返回异常结果");
      }
    } catch (Exception ex) {
      notifyWebhook("DB_HEALTH_CHECK", "数据库健康检查失败: " + ex.getMessage());
    }
  }

  private void notifyWebhook(String title, String message) {
    if (webhook.isBlank()) return;
    try {
      String body = "{\"title\":\"" + escape(title) + "\",\"message\":\"" + escape(message) + "\"}";
      HttpRequest request = HttpRequest.newBuilder()
          .uri(URI.create(webhook))
          .timeout(Duration.ofSeconds(8))
          .header("Content-Type", "application/json")
          .POST(HttpRequest.BodyPublishers.ofString(body))
          .build();
      httpClient.send(request, HttpResponse.BodyHandlers.discarding());
    } catch (Exception ignored) {
      // No-op: avoid monitor recursion on alert channel failures.
    }
  }

  private String escape(String value) {
    return value.replace("\\", "\\\\").replace("\"", "\\\"");
  }
}
