package com.nanri.aiimage.modules.ziniao.service;

import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoShopMatchResultVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class ZiniaoShopSwitchService {

    private final ZiniaoAuthService ziniaoAuthService;
    private final ZiniaoShopIndexService ziniaoShopIndexService;

    public ZiniaoShopMatchResultVo matchStoreByNameAcrossStaff(String targetShopName, Long preferUserId) {
        String normalizedShopName = normalizeShopName(targetShopName);
        if (normalizedShopName.isBlank()) {
            return emptyMatchResult();
        }

        ZiniaoAuthService.StoreMatchResult result = ziniaoAuthService.matchStoreByNameAcrossStaff(normalizedShopName, preferUserId);
        ZiniaoShopMatchResultVo vo = new ZiniaoShopMatchResultVo();
        vo.setMatched(result.matched());
        vo.setShopId(result.shopId());
        vo.setShopName(result.shopName());
        vo.setPlatform(result.platform());
        vo.setMatchedUserId(result.matchedUserId());
        vo.setOpenStoreUrl(result.openStoreUrl());
        vo.setMatchStatus(result.matched() ? ZiniaoShopIndexService.MATCH_STATUS_MATCHED : ZiniaoShopIndexService.MATCH_STATUS_PENDING);
        return vo;
    }

    public ZiniaoShopMatchResultVo findIndexedStoreByName(String targetShopName) {
        return ziniaoShopIndexService.findIndexedStoreByName(targetShopName);
    }

    public ZiniaoShopMatchResultVo emptyMatchResult() {
        ZiniaoShopMatchResultVo vo = new ZiniaoShopMatchResultVo();
        vo.setMatched(false);
        vo.setMatchStatus(ZiniaoShopIndexService.MATCH_STATUS_PENDING);
        vo.setMatchMessage("店铺名为空，无法匹配索引");
        return vo;
    }

    public String normalizeShopName(String value) {
        if (value == null) {
            return "";
        }
        return value.replace("\u3000", " ").trim();
    }

    public boolean isSkippableMatchError(BusinessException ex) {
        String message = ex == null ? null : ex.getMessage();
        if (message == null || message.isBlank()) {
            return false;
        }
        return (message.contains("code=40004")
                || message.contains("userId\u5b58\u5728\u65e0\u6548\u7684\u53c2\u6570\u503c")
                || message.contains("\u65e0\u6743\u9650")
                || message.contains("\u6ca1\u6709\u6743\u9650"))
                && !message.contains("\u767d\u540d\u5355");
    }
}
