package cn.qihangerp.erp.controller;

import cn.qihangerp.common.AjaxResult;
import cn.qihangerp.model.request.ExternalPddGoodsDetailRequest;
import cn.qihangerp.model.request.ExternalPddGoodsLatestCommitStatusRequest;
import cn.qihangerp.model.request.ExternalPddSkuCanonicalSyncRequest;
import cn.qihangerp.model.vo.ExternalPddGoodsDetailResultVo;
import cn.qihangerp.model.vo.ExternalPddSkuCanonicalSyncResultVo;
import cn.qihangerp.security.common.BaseController;
import cn.qihangerp.erp.config.ExternalGoodsApiLogProperties;
import cn.qihangerp.erp.support.ExternalGoodsRequestLogSupport;
import cn.qihangerp.service.external.ExternalPddGoodsDetailAppService;
import cn.qihangerp.service.external.ExternalPddGoodsLatestCommitStatusAppService;
import cn.qihangerp.service.external.ExternalPddSkuCanonicalSyncAppService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 拼多多专用外部接口（与 {@code /external/goods/upsert} 编排解耦）。
 * <ul>
 *   <li>{@code POST /external/pdd/goods/detail} — {@code pdd.goods.detail.get}</li>
 *   <li>{@code POST /external/pdd/goods/latest-commit-status} — {@code pdd.goods.latest.commit.status.get}</li>
 *   <li>{@code POST /external/pdd/goods/sku-canonical-sync} — 主数据在 detail 成功后回写 {@code o_goods_sku.canonical_ext.pddSkuId}</li>
 * </ul>
 * <p>改库存请使用 {@code POST /external/goods/pdd/quantity/update}（与 upsert 相同 out 键）。</p>
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/external/pdd/goods")
public class ExternalPddGoodsController extends BaseController {

    private final ExternalPddGoodsDetailAppService externalPddGoodsDetailAppService;
    private final ExternalPddGoodsLatestCommitStatusAppService externalPddGoodsLatestCommitStatusAppService;
    private final ExternalPddSkuCanonicalSyncAppService externalPddSkuCanonicalSyncAppService;
    private final ExternalGoodsApiLogProperties goodsApiLogProperties;

    @PostMapping("/detail")
    public AjaxResult detail(@RequestBody ExternalPddGoodsDetailRequest req) {
        if (goodsApiLogProperties.isLogFullRequest()) {
            log.info("[external/pdd/goods/detail] request={}", ExternalGoodsRequestLogSupport.pddDetailRequestJsonForLog(req));
        }
        if (req == null || req.getPddGoodsId() == null || req.getPddGoodsId() <= 0) {
            return AjaxResult.error("参数错误：pddGoodsId 不能为空且须为正数");
        }
        if (req.getPddPopAuth() == null) {
            return AjaxResult.error("参数错误：pddPopAuth 不能为空");
        }
        var auth = req.getPddPopAuth();
        if (!StringUtils.hasText(auth.getAppKey()) || !StringUtils.hasText(auth.getAppSecret())
                || !StringUtils.hasText(auth.getAccessToken())) {
            return AjaxResult.error("参数错误：pddPopAuth 需提供 appKey、appSecret、accessToken");
        }
        ExternalPddGoodsDetailResultVo vo = externalPddGoodsDetailAppService.fetchGoodsDetail(req);
        if (!Boolean.TRUE.equals(vo.getPopBizSuccess())) {
            return AjaxResult.error(StringUtils.hasText(vo.getMessage()) ? vo.getMessage() : "pdd.goods.detail.get 失败");
        }
        return AjaxResult.success(vo);
    }

    @PostMapping("/latest-commit-status")
    public AjaxResult latestCommitStatus(@RequestBody ExternalPddGoodsLatestCommitStatusRequest req) {
        if (goodsApiLogProperties.isLogFullRequest()) {
            log.info("[external/pdd/goods/latest-commit-status] goodsIdCount={}",
                    req != null && req.getPddGoodsIds() != null ? req.getPddGoodsIds().size() : 0);
        }
        if (req == null || req.getPddGoodsIds() == null || req.getPddGoodsIds().isEmpty()) {
            return AjaxResult.error("参数错误：pddGoodsIds 不能为空");
        }
        if (req.getPddPopAuth() == null) {
            return AjaxResult.error("参数错误：pddPopAuth 不能为空");
        }
        var auth = req.getPddPopAuth();
        if (!StringUtils.hasText(auth.getAppKey()) || !StringUtils.hasText(auth.getAppSecret())
                || !StringUtils.hasText(auth.getAccessToken())) {
            return AjaxResult.error("参数错误：pddPopAuth 需提供 appKey、appSecret、accessToken");
        }
        ExternalPddGoodsDetailResultVo vo = externalPddGoodsLatestCommitStatusAppService.fetchLatestCommitStatus(req);
        int n = req.getPddGoodsIds().size();
        log.info(
                "[external/pdd/goods/latest-commit-status] goodsIdCount={} popBizSuccess={} msg={}",
                n,
                vo.getPopBizSuccess(),
                vo.getMessage());
        if (!Boolean.TRUE.equals(vo.getPopBizSuccess())) {
            return AjaxResult.error(StringUtils.hasText(vo.getMessage()) ? vo.getMessage() : "pdd.goods.latest.commit.status.get 失败");
        }
        return AjaxResult.success(vo);
    }

    @PostMapping("/sku-canonical-sync")
    public AjaxResult skuCanonicalSync(@RequestBody ExternalPddSkuCanonicalSyncRequest req) {
        if (goodsApiLogProperties.isLogFullRequest()) {
            int rawLen = req != null && req.getGoodsDetailPopRaw() != null ? req.getGoodsDetailPopRaw().length() : 0;
            log.info("[external/pdd/goods/sku-canonical-sync] erpGoodsId={} goodsDetailPopRawLen={}",
                    req != null ? req.getErpGoodsId() : null, rawLen);
        }
        if (req == null || req.getErpGoodsId() == null || req.getErpGoodsId() <= 0) {
            return AjaxResult.error("参数错误：erpGoodsId 不能为空且须为正数");
        }
        if (!StringUtils.hasText(req.getGoodsDetailPopRaw())) {
            return AjaxResult.error("参数错误：goodsDetailPopRaw 不能为空");
        }
        ExternalPddSkuCanonicalSyncResultVo vo = externalPddSkuCanonicalSyncAppService.syncFromGoodsDetailPop(req);
        return AjaxResult.success(vo);
    }
}
