package com.red.circle.auth.common;

import com.red.circle.auth.dto.TokenCredentialCO;
import com.red.circle.auth.storage.RedCircleCredentialService;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.security.UserCredential;
import com.red.circle.other.inner.asserts.user.UserErrorCode;
import com.red.circle.other.inner.endpoint.user.user.UserProfileClient;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.other.inner.model.dto.user.account.UserAccountDTO;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.date.DateUtils;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * @author pengliang on 2023/12/20
 */
@Component
@RequiredArgsConstructor
public class ProcessToken {

  private final UserProfileClient userProfileClient;
  private final RedCircleCredentialService redCircleCredentialService;

  public String createIfAbsentUserCredentialToken(Long userId) {
    UserCredential credential = redCircleCredentialService.getByUserId(userId);
    if (Objects.nonNull(credential)) {
      return credential.token();
    }

    UserProfileDTO userProfile = userProfileClient.getByUserId(userId).getBody();
    ResponseAssert.notNull(UserErrorCode.USER_INFO_NOT_FOUND, userProfile);
    // 创建令牌
    UserCredential userCredential = new UserCredential();
    userCredential.setUserId(userProfile.getId());
    userCredential.setSysOrigin(userProfile.getOriginSys());
    userCredential.setExpireTime(DateUtils.nowPlusDays(30).getTime());
    userCredential.setReleaseTime(DateUtils.now().getTime());
    userCredential.setVersion("v2");
    redCircleCredentialService.save(userCredential);
    return userCredential.token();
  }

  public TokenCredentialCO createUserCredential(UserAccountDTO account) {
    ResponseAssert.notNull(UserErrorCode.USER_INFO_NOT_FOUND, account);
    // 创建令牌
    UserCredential userCredential = new UserCredential();
    userCredential.setUserId(account.getUserProfile().getId());
    userCredential.setSysOrigin(account.getUserProfile().getOriginSys());
    userCredential.setExpireTime(DateUtils.nowPlusDays(30).getTime());
    userCredential.setReleaseTime(DateUtils.now().getTime());
    userCredential.setVersion("v2");
    redCircleCredentialService.save(userCredential);
    account.setToken(userCredential.token());

    // 创建返回凭证信息
    TokenCredentialCO co = new TokenCredentialCO();
    co.setToken(userCredential.token());
    co.setUserProfile(account.getUserProfile());
    co.setUserCredential(userCredential);
    co.setUserSig(account.getUserSig());
    if (CollectionUtils.isNotEmpty(account.getExtValues())) {
      account.getExtValues().forEach(co::putExtField);
    }
    return co;
  }

}
