package com.xiang.xservice.application.script.domain.service;


import com.aliyun.alidns20150109.Client;
import com.aliyun.alidns20150109.models.AddDomainRecordRequest;
import com.aliyun.alidns20150109.models.DescribeSubDomainRecordsRequest;
import com.aliyun.alidns20150109.models.DescribeSubDomainRecordsResponse;
import com.aliyun.alidns20150109.models.DescribeSubDomainRecordsResponseBody;
import com.aliyun.alidns20150109.models.UpdateDomainRecordRequest;
import com.aliyun.teaopenapi.models.Config;
import com.xiang.xservice.application.script.domain.config.AliyunDnsPropertyConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: xiang
 * @Date: 2025-06-10 16:48
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class IDomainServiceImpl implements IDomainService {

    private static final String ACCESS_KEY_ID = "LTAI5tDMjaVF8Bbqcpp4dmvP";
    private static final String ACCESS_KEY_SECRET = "nkmnaNjWQy5984C5kjyS0oDmdMKGQd";
    /**
     *  根域名
     */
    private static final String DOMAIN_NAME = "xiangtech.xyz";
    /**
     * 主机记录，例如 home.example.com
     */
    private final AliyunDnsPropertyConfig aliyunDnsPropertyConfig;
    private static final String TYPE = "A";

    private final DingTalkScriptDomainService dingTalkService;
    @Override
    public void dynamicDomainAnalysis(String publicIp) throws Exception {
        Client client = createClient();

        for (String rr : aliyunDnsPropertyConfig.getRR()) {
            // 查询记录
            DescribeSubDomainRecordsRequest query = new DescribeSubDomainRecordsRequest()
                    .setSubDomain(rr + "." + DOMAIN_NAME)
                    .setType(TYPE);
            DescribeSubDomainRecordsResponse response = client.describeSubDomainRecords(query);
            List<DescribeSubDomainRecordsResponseBody.DescribeSubDomainRecordsResponseBodyDomainRecordsRecord> records =
                    response.getBody().getDomainRecords().getRecord();

            if (records.isEmpty()) {
                log.info("未找到记录，添加记录..., ip:{}", publicIp);
                addDnsRecord(client, publicIp, rr);
                dingTalkService.sendScriptMsg("动态解析公网ip成功，域名：" + rr + "." + DOMAIN_NAME + ", 新ip:" + publicIp);
            } else {
                String recordId = records.get(0).getRecordId();
                String currentValue = records.get(0).getValue();
                if (!publicIp.equals(currentValue)) {
                    log.info("IP变更，更新记录...,ip:{}", publicIp);
                    updateDnsRecord(client, recordId, publicIp, rr);
                    dingTalkService.sendScriptMsg("动态解析公网ip成功，域名：" + rr + "." + DOMAIN_NAME + ", 新ip:" + publicIp);
                } else {
                    log.info("ip未变更，无需修改，ip:{}", publicIp);
                }
            }
        }
    }

    private Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(ACCESS_KEY_ID)
                .setAccessKeySecret(ACCESS_KEY_SECRET)
                .setEndpoint("alidns.cn-hangzhou.aliyuncs.com");
        return new Client(config);
    }

    private void updateDnsRecord(Client client, String recordId, String newIp, String rr) throws Exception {
        UpdateDomainRecordRequest request = new UpdateDomainRecordRequest()
                .setRecordId(recordId)
                .setRR(rr)
                .setType(TYPE)
                .setValue(newIp);
        client.updateDomainRecord(request);
        log.info("更新成功: ，newIP:{}", newIp);
    }

    private void addDnsRecord(Client client, String ip, String rr) throws Exception {
        AddDomainRecordRequest request = new AddDomainRecordRequest()
                .setDomainName(DOMAIN_NAME)
                .setRR(rr)
                .setType(TYPE)
                .setValue(ip);
        client.addDomainRecord(request);
        log.info("添加成功: ip:{}", ip);
    }
}
