package com.yolo.keyboard.api.invitecode;

import cn.hutool.core.util.RandomUtil;
import com.yolo.keyboard.dal.dataobject.userinvitecodes.KeyboardUserInviteCodesDO;
import com.yolo.keyboard.dal.mysql.userinvitecodes.KeyboardUserInviteCodesMapper;
import com.yolo.keyboard.module.system.api.invitecode.UserInviteCodeApi;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 用户邀请码 API 实现类
 *
 * @author ziin
 */
@Service
public class UserInviteCodeApiImpl implements UserInviteCodeApi {

    @Resource
    private KeyboardUserInviteCodesMapper userInviteCodesMapper;

    @Override
    public String createInviteCodeForAgent(Long userId, Long tenantId) {
        String inviteCode = generateUniqueInviteCode();
        KeyboardUserInviteCodesDO inviteCodeDO = KeyboardUserInviteCodesDO.builder()
                .code(inviteCode)
                .ownerSystemUserId(userId)
                .ownerTenantId(tenantId)
                .status((short) 1)
                .createdAt(LocalDateTime.now())
                .usedCount(0)
                .inviteType("AGENT")
                .build();
        userInviteCodesMapper.insert(inviteCodeDO);
        return inviteCode;
    }

    /**
     * 生成唯一的6位邀请码（字母和数字混合）
     */
    private String generateUniqueInviteCode() {
        String code;
        int maxAttempts = 100;
        int attempt = 0;
        do {
            code = RandomUtil.randomString("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 6);
            attempt++;
            if (attempt >= maxAttempts) {
                throw new RuntimeException("无法生成唯一的邀请码，请稍后重试");
            }
        } while (userInviteCodesMapper.selectOne(KeyboardUserInviteCodesDO::getCode, code) != null);
        return code;
    }
}
