package com.seer.teach.mp.app.service.impl;

import com.seer.teach.mp.app.controller.req.JsapiSignatureReq;
import com.seer.teach.mp.app.controller.resp.JsapiSignatureResp;
import com.seer.teach.mp.app.service.IAppMpSignatureService;
import com.seer.teach.mp.factory.MpServiceFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;

/**
 * 微信公众号JS-SDK签名服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AppMpSignatureServiceImpl implements IAppMpSignatureService {

    private final MpServiceFactory mpServiceFactory;

    @Override
    public JsapiSignatureResp generateJsapiSignature(JsapiSignatureReq req) {
        try {
            // 获取WxMpService实例
            var mpService = mpServiceFactory.getRequiredMpService(req.getAppId());

            WxJsapiSignature wxJsapiSignature = mpService.createJsapiSignature(req.getUrl());

            return new JsapiSignatureResp(wxJsapiSignature.getTimestamp(), wxJsapiSignature.getNonceStr(), wxJsapiSignature.getSignature(), req.getAppId());
        } catch (WxErrorException e) {
            log.error("生成JS-SDK签名失败，appId: {}, url: {}", req.getAppId(), req.getUrl(), e);
            throw new RuntimeException("生成JS-SDK签名失败", e);
        }
    }
}