package com.red.circle.other.app.command.user.query;



import com.red.circle.common.business.core.enums.CommonErrorEnum;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.dto.AppCommand;
import com.red.circle.other.app.dto.clientobject.user.user.LoginLoggerCO;
import com.red.circle.other.domain.gateway.user.UserRunProfileTransportGateway;
import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.other.infra.database.cache.service.user.CacheEnumConfigManagerService;
import com.red.circle.other.infra.database.rds.entity.user.user.AuthType;
import com.red.circle.other.infra.database.rds.entity.user.user.LoginLogger;
import com.red.circle.other.infra.database.rds.enums.OtherConfigEnum;
import com.red.circle.other.infra.database.rds.service.user.user.AuthTypeService;
import com.red.circle.other.infra.database.rds.service.user.user.LoginLoggerService;
import com.red.circle.other.inner.enums.user.AuthTypeEnum;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 用户登录日志信息查询
 *
 * @author zongpubin on 2023/11/27
 */
@Component
@AllArgsConstructor
public class UserLoginLoggerQueryExe {

  private final AuthTypeService authTypeService;
  private final LoginLoggerService loginLoggerService;
  private final UserRunProfileTransportGateway userRunProfileTransportGateway;
  private final CacheEnumConfigManagerService cacheEnumConfigManagerService;

  public LoginLoggerCO execute(AppCommand cmd) {

    ResponseAssert.isTrue(CommonErrorEnum.NOT_OPEN_ERROR,
        cacheEnumConfigManagerService.getValBool(OtherConfigEnum.USER_LOGIN_BY_OPEN_ID_FACEBOOK,
            cmd.getReqSysOrigin().getOrigin()));

    LoginLogger loginLogger = loginLoggerService.getByDeviceId(cmd.getReqImei());
    ResponseAssert.notNull(CommonErrorEnum.NOT_FOUND_RECORD_INFO, loginLogger);

    UserProfile userProfile = userRunProfileTransportGateway.getByUserId(loginLogger.getUserId());

    ResponseAssert.notNull(CommonErrorEnum.NOT_FOUND_RECORD_INFO, userProfile);

    AuthType authType = authTypeService.getAuthInfoByUserId(AuthTypeEnum.FACEBOOK.name(),
        userProfile.getId());

    ResponseAssert.notNull(CommonErrorEnum.NOT_FOUND_RECORD_INFO, authType);

    return LoginLoggerCO.builder()
        .openId(authType.getOpenId().substring(0, authType.getOpenId().lastIndexOf("_"))
            .trim())
        .userAvatar(userProfile.getUserAvatar())
        .build();
  }
}
