package com.ycwl.basic.notify.adapters;

import cn.hutool.http.HttpUtil;
import com.ycwl.basic.notify.entity.NotifyContent;
import com.ycwl.basic.notify.entity.ServerChanConfig;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ServerChanNotifyAdapter implements INotifyAdapter {
    ServerChanConfig config;

    @Override
    public void loadConfig(Map<String, String> _config) {
        ServerChanConfig config = new ServerChanConfig();
        config.setKey(_config.get("key"));
        config.checkEverythingOK();
        this.config = config;
    }

    @Override
    public void sendTo(NotifyContent notifyContent, String to) {
        scSend(notifyContent.getTitle(), notifyContent.getContent(), config.getKey());
    }

    public static String scSend(String title, String content, String key) {
        try {
            String api;

            // 判断 sendkey 是否以 "sctp" 开头，并提取数字部分拼接 URL
            if (key.startsWith("sctp")) {
                Pattern pattern = Pattern.compile("sctp(\\d+)t");
                Matcher matcher = pattern.matcher(key);
                if (matcher.find()) {
                    String num = matcher.group(1);
                    api = "https://" + num + ".push.ft07.com/send/" + key +".send";
                } else {
                    throw new IllegalArgumentException("Invalid sendkey format for sctp");
                }
            } else {
                api = "https://sctapi.ftqq.com/" + key + ".send";
            }
            Map<String, Object> body = new HashMap<>();
            body.put("title", title);
            body.put("desp", content);
            return HttpUtil.post(api, body);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
