package cn.reghao.tnb.user.app.service;

import cn.reghao.tnb.account.api.dto.AccountInfo;
import cn.reghao.tnb.account.api.dto.CrawledUser;
import cn.reghao.tnb.account.api.iface.AccountQuery;
import cn.reghao.tnb.user.app.db.mapper.UserProfileMapper;
import cn.reghao.tnb.user.app.model.po.UserProfile;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

/**
 * @author reghao
 * @date 2023-05-31 11:12:08
 */
@Service
public class CrawledUserService {
    @DubboReference(check = false, retries = 0, timeout = 60_000)
    private AccountQuery accountQuery;
    private final UserProfileMapper userProfileMapper;

    public CrawledUserService(UserProfileMapper userProfileMapper) {
        this.userProfileMapper = userProfileMapper;
    }

    public Long getUserId(String username) {
        AccountInfo accountInfo = accountQuery.getByUsername(username);
        if (accountInfo != null) {
            String userIdStr = accountInfo.getUserId();
            long userId = accountQuery.getUserIdLong(userIdStr);
            return userId;
        }

        return null;
    }

    public synchronized Long createAccount(CrawledUser crawledUser) {
        Long userId = accountQuery.createCrawledAccount(crawledUser);
        UserProfile userProfile = userProfileMapper.findByUserId(userId);
        if (userProfile == null) {
            int gender = crawledUser.getGender();
            String signature = crawledUser.getSignature();
            userProfile = new UserProfile(userId, gender, signature);
            userProfileMapper.save(userProfile);
        }

        return userId;
    }
}
