package com.red.circle.other.app.service.user.user;

import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.tool.core.date.TimestampUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.red.circle.common.business.dto.cmd.CreateSpecialIdCmd;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.other.infra.database.mongo.entity.user.profile.UserSpecialId;
import com.red.circle.other.infra.database.mongo.service.user.profile.UserSpecialIdService;
import com.red.circle.other.infra.enums.user.user.SpecialIdPatternEnum;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RequiredArgsConstructor
public class SpecialIdServiceImpl implements SpecialIdService {

    private final UserSpecialIdService userSpecialIdService;

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public boolean createSpecialId(CreateSpecialIdCmd cmd) {
        // 验证账号是否符合当前等级的靓号规则
        boolean isValidForLevel = SpecialIdPatternEnum.isValidForLevel(
            cmd.getAccount(),
            cmd.getWealthLevel()
        );
        ResponseAssert.isTrue(CommonErrorCode.SAVE_FAILURE,"The account does not meet the current wealth level rules", isValidForLevel);

        // 检查靓号是否已存在
        boolean exists = userSpecialIdService.exists(cmd.getReqSysOrigin().getOrigin(), cmd.getAccount());
        ResponseAssert.isFalse(CommonErrorCode.SAVE_FAILURE,  "The beautiful number already exists",exists);

            // 检查用户是否已有靓号，如果有则删除
            UserSpecialId oldSpecialId = userSpecialIdService.getByUserId(cmd.getUserId());
            if (oldSpecialId != null) {
                userSpecialIdService.remove(oldSpecialId.getId());
            }

            // 创建新靓号
            UserSpecialId specialIdCmd = new UserSpecialId();
            specialIdCmd.setSysOrigin(cmd.getReqSysOrigin().getOrigin());
            specialIdCmd.setAccount(cmd.getAccount());
            specialIdCmd.setUserId(cmd.getUserId());
            // 设置365天后过期
            specialIdCmd.setExpiredTime(TimestampUtils.dateTimePlusDays(TimestampUtils.now(),365));

            userSpecialIdService.add(specialIdCmd);

            log.info("创建靓号成功, userId:{}, account:{}", cmd.getUserId(), cmd.getAccount());
            return true;

    }
}
