package com.xunhong.erp.turbo.user.app.executor.query;

import cn.dev33.satoken.secure.BCrypt;
import com.xunhong.erp.turbo.api.facade.dto.qry.WxMaOpenidQry;
import com.xunhong.erp.turbo.api.user.dto.cmd.UserAuthCreateCmd;
import com.xunhong.erp.turbo.api.user.dto.cmd.UserUpdateWxCmd;
import com.xunhong.erp.turbo.api.user.dto.enums.SocialTypeEnum;
import com.xunhong.erp.turbo.api.user.dto.vo.UserAuthVO;
import com.xunhong.erp.turbo.user.app.assembler.UserAuthAssembler;
import com.xunhong.erp.turbo.user.domain.entity.UserAuth;
import com.xunhong.erp.turbo.user.domain.gateway.UserAuthGateway;
import com.xunhong.erp.turbo.user.domain.gateway.UserGateway;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author shenyifei
 */
@Component
@RequiredArgsConstructor
public class WxMaCodeLoginQryExe {
	private final UserAuthGateway userAuthGateway;
	private final UserAuthAssembler userAuthAssembler;

	private final UserGateway userGateway;

	public UserAuthVO execute(WxMaOpenidQry wxMaOpenidQry) {
		String unionid = wxMaOpenidQry.getUnionid();
		UserAuth userAuth = userAuthGateway.getByAccount(unionid, SocialTypeEnum.WX_UNION_ID);

		if (Objects.isNull(userAuth)) {
			UserAuthCreateCmd userAuthCreateCmd = UserAuthCreateCmd.builder().socialType(SocialTypeEnum.ACCOUNT)
				.username(unionid)
				.password(BCrypt.hashpw(unionid))
				.socialType(SocialTypeEnum.WX_UNION_ID)
				.isAdmin(Boolean.FALSE)
				.build();
			userAuth = userAuthGateway.register(userAuthCreateCmd);
		}

		Long userId = userAuth.getUserId();
		UserUpdateWxCmd userUpdateWxCmd = new UserUpdateWxCmd();
		userUpdateWxCmd.setUserId(userId);
		userUpdateWxCmd.setUnionid(unionid);
		if (Objects.nonNull(wxMaOpenidQry.getMaOpenid())) {
			userUpdateWxCmd.setMaOpenid(wxMaOpenidQry.getMaOpenid());
		}
		if (Objects.nonNull(wxMaOpenidQry.getMpOpenid())) {
			userUpdateWxCmd.setMpOpenid(wxMaOpenidQry.getMpOpenid());
		}
		userGateway.updateWx(userUpdateWxCmd);

		return userAuthAssembler.toUserAuthVO(userAuth);
	}
}
