package cn.qihangerp.service.external.impl;

import cn.qihangerp.model.request.ExternalGoodsUpsertRequest;
import cn.qihangerp.model.request.ExternalPddGoodsDetailRequest;
import cn.qihangerp.model.vo.ExternalPddGoodsDetailResultVo;
import cn.qihangerp.service.external.ExternalPddGoodsDetailAppService;
import cn.qihangerp.service.external.pdd.ExternalPddProperties;
import cn.qihangerp.service.external.pdd.PddOpenApiSupport;
import cn.qihangerp.service.external.pdd.PddPopClient;
import cn.qihangerp.service.external.shop.PddShopCredential;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author guochengyu
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ExternalPddGoodsDetailAppServiceImpl implements ExternalPddGoodsDetailAppService {

    private final ExternalPddProperties props;
    private final PddPopClient pddPopClient;

    @Override
    public ExternalPddGoodsDetailResultVo fetchGoodsDetail(ExternalPddGoodsDetailRequest req) {
        if (req == null || req.getPddGoodsId() == null || req.getPddGoodsId() <= 0) {
            return ExternalPddGoodsDetailResultVo.builder()
                    .popBizSuccess(false)
                    .message("pddGoodsId 无效")
                    .popResponseBody(null)
                    .build();
        }
        PddShopCredential cred = resolveCredential(req);
        if (cred == null || !StringUtils.hasText(cred.getAppKey()) || !StringUtils.hasText(cred.getAppSecret())
                || !StringUtils.hasText(cred.getAccessToken())) {
            return ExternalPddGoodsDetailResultVo.builder()
                    .popBizSuccess(false)
                    .message("pddPopAuth 不完整：需 appKey、appSecret、accessToken")
                    .popResponseBody(null)
                    .build();
        }
        String gateway = StringUtils.hasText(cred.getGatewayUrl()) ? cred.getGatewayUrl() : props.getGatewayUrl();
        if (!StringUtils.hasText(gateway)) {
            return ExternalPddGoodsDetailResultVo.builder()
                    .popBizSuccess(false)
                    .message("未配置 POP gatewayUrl（请求体或 external.pdd.gateway-url）")
                    .popResponseBody(null)
                    .build();
        }
        try {
            String raw = pddPopClient.invokeTopLevelBiz(
                    gateway,
                    cred.getAppKey(),
                    cred.getAppSecret(),
                    cred.getAccessToken(),
                    "pdd.goods.detail.get",
                    PddOpenApiSupport.goodsDetailGetTopLevelParams(req.getPddGoodsId()));
            boolean ok = !PddOpenApiSupport.isError(raw);
            return ExternalPddGoodsDetailResultVo.builder()
                    .popBizSuccess(ok)
                    .message(ok ? "pdd.goods.detail.get 调用成功" : ("pdd.goods.detail.get 失败: " + PddOpenApiSupport.formatError(raw)))
                    .popResponseBody(raw)
                    .build();
        } catch (Exception e) {
            log.warn("[PDD] pdd.goods.detail.get exception pddGoodsId={} err={}", req.getPddGoodsId(), e.getMessage(), e);
            return ExternalPddGoodsDetailResultVo.builder()
                    .popBizSuccess(false)
                    .message(e.getMessage())
                    .popResponseBody(null)
                    .build();
        }
    }

    private static PddShopCredential resolveCredential(ExternalPddGoodsDetailRequest req) {
        if (req == null || req.getPddPopAuth() == null) {
            return null;
        }
        ExternalGoodsUpsertRequest.PddPopAuth a = req.getPddPopAuth();
        PddShopCredential c = new PddShopCredential();
        c.setAppKey(trimToNull(a.getAppKey()));
        c.setAppSecret(trimToNull(a.getAppSecret()));
        c.setAccessToken(trimToNull(a.getAccessToken()));
        if (StringUtils.hasText(a.getGatewayUrl())) {
            c.setGatewayUrl(a.getGatewayUrl().trim());
        }
        c.setSource("REQUEST");
        return c;
    }

    private static String trimToNull(String s) {
        if (!StringUtils.hasText(s)) {
            return null;
        }
        return s.trim();
    }
}
