package com.test.bijihoudaun.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.bijihoudaun.entity.RegistrationCode;
import com.test.bijihoudaun.mapper.RegistrationCodeMapper;
import com.test.bijihoudaun.service.RegistrationCodeService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
@Transactional
public class RegistrationCodeServiceImpl extends ServiceImpl<RegistrationCodeMapper, RegistrationCode> implements RegistrationCodeService {

    @Override
    public String generateCode(String creator) {
        RegistrationCode registrationCode = new RegistrationCode();
        String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
        registrationCode.setCode(code);
        registrationCode.setCreatedBy(creator);
        registrationCode.setCreatedAt(LocalDateTime.now().toString());
        registrationCode.setExpiryTime(LocalDateTime.now().plusDays(1).toString());
        save(registrationCode);
        return code;
    }

    @Override
    @Transactional
    public boolean validateCode(String code) {
        QueryWrapper<RegistrationCode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", code);
        RegistrationCode registrationCode = getOne(queryWrapper);

        if (ObjectUtil.isNull(registrationCode)) {
            return false;
        }

        LocalDateTime expiryTime = LocalDateTime.parse(registrationCode.getExpiryTime());
        if (expiryTime.isBefore(LocalDateTime.now())) {
            remove(queryWrapper); // 注册码过期，删除
            return false;
        }

        // 验证成功后立即删除，确保一次性使用
        remove(queryWrapper);
        return true;
    }

    @Override
    @Scheduled(cron = "0 0 1 * * ?") // 每天凌晨1点执行
    public void deleteExpiredCodes() {
        remove(new QueryWrapper<RegistrationCode>().lt("expiry_time", LocalDateTime.now().toString()));
    }
}