package com.tzld.piaoquan.api.component;

import com.tzld.piaoquan.api.common.enums.ExceptionEnum;
import com.tzld.piaoquan.api.common.exception.CommonException;
import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class VideoVectorProxyService {

    @Autowired
    private HttpPoolClient httpPoolClient;

    @Value("${video.vector.api.host:http://api-internal.piaoquantv.com/videoVector}")
    private String videoVectorApiHost;

    public String get(String path) {
        String url = buildUrl(path);
        try {
            return requireResponse(httpPoolClient.get(url), path);
        } catch (IOException e) {
            log.error("VideoVectorProxyService GET failed, path={}", path, e);
            throw new CommonException(ExceptionEnum.SYSTEM_ERROR, e);
        }
    }

    public String post(String path, String requestBody) {
        String url = buildUrl(path);
        try {
            return requireResponse(httpPoolClient.post(url, requestBody), path);
        } catch (IOException e) {
            log.error("VideoVectorProxyService POST failed, path={}", path, e);
            throw new CommonException(ExceptionEnum.SYSTEM_ERROR, e);
        }
    }

    private String buildUrl(String path) {
        return videoVectorApiHost.replaceAll("/+$", "") + "/" + path;
    }

    private String requireResponse(String response, String path) {
        if (response == null) {
            log.error("VideoVectorProxyService upstream returned no response, path={}", path);
            throw new CommonException(ExceptionEnum.SYSTEM_ERROR);
        }
        return response;
    }
}
