package com.hertz.modules.system.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.UUID;
import com.hertz.common.exception.BusinessException;
import com.hertz.modules.system.dto.AuthDtos;
import com.hertz.modules.system.service.CaptchaService;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class CaptchaServiceImpl implements CaptchaService {

  private final StringRedisTemplate redisTemplate;

  public CaptchaServiceImpl(StringRedisTemplate redisTemplate) {
    this.redisTemplate = redisTemplate;
  }

  @Override
  public AuthDtos.CaptchaResponse generateCaptcha() {
    // Width: 120, Height: 40, Code Count: 4, Interference Line Count: 10
    LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120, 40, 4, 10);
    String uuid = UUID.fastUUID().toString(true);
    String code = lineCaptcha.getCode();
    
    // Store in Redis with 5 minutes expiration
    redisTemplate.opsForValue().set("captcha:" + uuid, Objects.requireNonNull(code), 5, TimeUnit.MINUTES);
    
    return new AuthDtos.CaptchaResponse(uuid, lineCaptcha.getImageBase64Data());
  }

  @Override
  public void validateCaptcha(String uuid, String code) {
    if (uuid == null || uuid.isBlank() || code == null || code.isBlank()) {
      throw new BusinessException(40001, "验证码不能为空");
    }
    String key = "captcha:" + uuid;
    String cachedCode = redisTemplate.opsForValue().get(key);
    
    if (cachedCode == null) {
      throw new BusinessException(40002, "验证码已过期");
    }
    
    if (!code.equalsIgnoreCase(cachedCode)) {
      throw new BusinessException(40003, "验证码错误");
    }
    
    // Validate once, then delete to prevent replay
    redisTemplate.delete(key);
  }
}
