package com.pm.sms;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

// 网线通道 - API方式
public class ApiSmsSender implements SmsSender {
    private static final Logger log = LoggerFactory.getLogger(ApiSmsSender.class);
    private static final String API_URL = "https://sms.provider.com/send";
    private static final String API_KEY = "YOUR_API_KEY";

    @Override
    public boolean sendAlert(String phone, String message) {
        HttpURLConnection connection = null;
        try {
            // 创建URL连接
            URL url = new URL(API_URL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            // 构建JSON请求体
            String jsonBody = String.format(
                    "{\"key\":\"%s\",\"phone\":\"%s\",\"msg\":\"%s\"}",
                    API_KEY,
                    phone,
                    URLEncoder.encode(message, "UTF-8")
            );

            // 发送请求
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 处理响应
            int statusCode = connection.getResponseCode();
            if (statusCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    log.info("短信发送成功: {}", phone);
                    return true;
                }
            } else {
                log.warn("短信发送失败，状态码: {}", statusCode);
                return false;
            }
        } catch (Exception e) {
            log.error("API短信发送失败", e);
            return false;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
}
