package cn.qihangerp.service.external.impl;

import cn.qihangerp.model.request.ExternalGoodsUpsertRequest;
import cn.qihangerp.model.request.ExternalPddGoodsLatestCommitStatusRequest;
import cn.qihangerp.model.vo.ExternalPddGoodsDetailResultVo;
import cn.qihangerp.service.external.ExternalPddGoodsLatestCommitStatusAppService;
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.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 仅调用 POP，返回原始 JSON 供主数据解析 {@code goods_latest_commit_status_get_response}。
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ExternalPddGoodsLatestCommitStatusAppServiceImpl implements ExternalPddGoodsLatestCommitStatusAppService {

    private final ExternalPddProperties props;
    private final PddPopClient pddPopClient;

    @Override
    public ExternalPddGoodsDetailResultVo fetchLatestCommitStatus(ExternalPddGoodsLatestCommitStatusRequest req) {
        if (req == null || CollectionUtils.isEmpty(req.getPddGoodsIds())) {
            return ExternalPddGoodsDetailResultVo.builder()
                    .popBizSuccess(false)
                    .message("pddGoodsIds 不能为空")
                    .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();
        }
        List<Long> ids = req.getPddGoodsIds().stream().filter(id -> id != null && id > 0).toList();
        if (ids.isEmpty()) {
            return ExternalPddGoodsDetailResultVo.builder()
                    .popBizSuccess(false)
                    .message("pddGoodsIds 无有效正数")
                    .popResponseBody(null)
                    .build();
        }
        try {
            String raw = pddPopClient.invokeTopLevelBiz(
                    gateway,
                    cred.getAppKey(),
                    cred.getAppSecret(),
                    cred.getAccessToken(),
                    "pdd.goods.latest.commit.status.get",
                    PddOpenApiSupport.goodsLatestCommitStatusGetTopLevelParams(ids));
            boolean ok = !PddOpenApiSupport.isError(raw);
            return ExternalPddGoodsDetailResultVo.builder()
                    .popBizSuccess(ok)
                    .message(ok ? "pdd.goods.latest.commit.status.get 调用成功" : ("pdd.goods.latest.commit.status.get 失败: " + PddOpenApiSupport.formatError(raw)))
                    .popResponseBody(raw)
                    .build();
        } catch (Exception e) {
            log.warn("[PDD] pdd.goods.latest.commit.status.get exception err={}", e.getMessage(), e);
            return ExternalPddGoodsDetailResultVo.builder()
                    .popBizSuccess(false)
                    .message(e.getMessage())
                    .popResponseBody(null)
                    .build();
        }
    }

    private static PddShopCredential resolveCredential(ExternalPddGoodsLatestCommitStatusRequest 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();
    }
}
