package com.common.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import com.common.entity.BlacklistApiProperties;
import com.common.entity.BlacklistRequest;
import com.common.entity.BlockResponse;
@Service
public class BlacklistApiService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private BlacklistApiProperties apiProperties;

    public BlockResponse addToBlacklist(String ip, String age, String enable) {
        String url = apiProperties.getUrl();

        // 构建请求体
        BlacklistRequest requestBody = new BlacklistRequest(ip, age, enable);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // Basic Auth 编码（密码含特殊字符 % 无需额外处理，Base64 直接编码字节）
        String auth = apiProperties.getUsername() + ":" + apiProperties.getPassword();
        byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.ISO_8859_1));
        String authHeader = "Basic " + new String(encodedAuth, StandardCharsets.ISO_8859_1);
        headers.set("Authorization", authHeader);

        HttpEntity<BlacklistRequest> entity = new HttpEntity<>(requestBody, headers);

        // 发送 POST 请求
        ResponseEntity<BlockResponse> response = restTemplate.exchange(
                url, HttpMethod.POST, entity, BlockResponse.class);

        return response.getBody();
    }
}