package com.liquidnet.service.adam.service.impl;

import com.liquidnet.common.third.secureaccess.biz.NiaAuthBiz;
import com.liquidnet.common.third.secureaccess.model.NiaAuthRequest;
import com.liquidnet.common.third.secureaccess.model.NiaAuthResult;
import com.liquidnet.common.third.secureaccess.util.NiaPidUtils;
import com.liquidnet.service.adam.constant.AdamTpaConst;
import com.liquidnet.service.adam.dto.AdamNiaLoginParam;
import com.liquidnet.service.adam.dto.vo.AdamNiaAuthVo;
import com.liquidnet.service.adam.service.IAdamNiaLoginService;
import com.liquidnet.service.base.ResponseDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class AdamNiaLoginServiceImpl implements IAdamNiaLoginService {

    private final NiaAuthBiz niaAuthBiz;

    @Override
    public ResponseDto<?> login(AdamNiaLoginParam param) {
        if (!niaAuthBiz.isReady()) {
            return ResponseDto.failure("10005", "网证认证服务暂未开通，请稍后再试");
        }

        log.info("[nia-login] 请求 bizSeq={}, idCardAuthDataLen={}",
                param.getBizSeq(), param.getIdCardAuthData() == null ? 0 : param.getIdCardAuthData().length());

        NiaAuthResult authResult = niaAuthBiz.authenticate(NiaAuthRequest.builder()
                .bizSeq(param.getBizSeq())
                .idCardAuthData(param.getIdCardAuthData())
                .build());

        if (!authResult.isSuccess()) {
            log.warn("[nia-login] 认证失败 bizSeq={}, stage={}, code={}, desc={}",
                    param.getBizSeq(),
                    authResult.getStage(),
                    authResult.getResultCode(),
                    authResult.getResultDesc());
            String errMsg = authResult.getResultDesc() != null && !authResult.getResultDesc().isEmpty()
                    ? authResult.getResultDesc() : "网证认证失败，请重试";
            return ResponseDto.failure("10005", errMsg);
        }
        if (!NiaPidUtils.isValidOpenId(authResult.getOpenId())) {
            log.warn("[nia-login] PID标识解析失败 bizSeq={}", param.getBizSeq());
            return ResponseDto.failure("10005", "网证认证失败，请重试");
        }

        AdamNiaAuthVo authVo = AdamNiaAuthVo.builder()
                .platform(AdamTpaConst.PLATFORM_NIA)
                .openId(authResult.getOpenId())
                .build();
        log.info("[nia-login] 认证成功 bizSeq={}, bizSerialNo={}, openId={}",
                param.getBizSeq(), authResult.getBizSerialNo(), authResult.getOpenId());
        return ResponseDto.success(authVo);
    }
}
