package edu.whut.infrastructure.gateway;
import edu.whut.types.enums.ResponseCode;
import edu.whut.types.exception.AppException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 拼团回调服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GroupBuyNotifyService {

    private final OkHttpClient okHttpClient;

    /**
     * 将拼团系统的回调数据通过 HTTP POST 发送给指定的外部接口
     */
    public String groupBuyNotify(String apiUrl, String notifyRequestDTOJSON) throws Exception {
        try {
            // 1. 构造请求体，指定 Content-Type 为 application/json
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, notifyRequestDTOJSON);

            // 2. 构建 HTTP POST 请求
            Request request = new Request.Builder()
                    .url(apiUrl)                         // 回调目标 URL
                    .post(body)                          // POST JSON 请求体
                    .addHeader("content-type", "application/json")
                    .build();

            // 3. 执行同步调用
            Response response = okHttpClient.newCall(request).execute();

            // 4. 读取并返回响应内容
            return response.body().string();
        } catch (Exception e) {
            // 发生任何网络或解析异常，都在日志中记录并统一抛出业务异常
            log.error("拼团回调 HTTP 接口服务异常，apiUrl={}", apiUrl, e);
            throw new AppException(ResponseCode.HTTP_EXCEPTION);
        }
    }

}
