package cn.meowrain.aioj.backend.userservice.service;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.ActiveProfiles;

import static org.junit.jupiter.api.Assertions.*;

/**
 * 邮件服务测试类
 */
@Slf4j
@SpringBootTest
@ActiveProfiles("test")
class EmailServiceTest {

	@Autowired
	private EmailService emailService;

	@Autowired
	private StringRedisTemplate redisTemplate;

	/**
	 * 测试发送验证码邮件
	 * 注意：运行此测试前，请将下面的邮箱地址替换为你自己的邮箱
	 */
	@Test
	void testSendVerifyCode() {
		// TODO: 替换成你的真实邮箱地址
		String testEmail = "meowrain@126.com";

		log.info("开始发送验证码到邮箱: {}", testEmail);

		// 发送验证码
		assertDoesNotThrow(() -> emailService.sendVerifyCode(testEmail));

		log.info("验证码邮件发送成功，请检查邮箱（含垃圾邮件文件夹）");

		// 验证 Redis 中是否存储了验证码
		String redisKey = "email:code:" + testEmail;
		String code = redisTemplate.opsForValue().get(redisKey);

		assertNotNull(code, "验证码应该存储在 Redis 中");
		log.info("Redis 中存储的验证码: {}", code);

		// 提示用户
		log.info("===============================================");
		log.info("请登录邮箱查看验证码: {}", testEmail);
		log.info("验证码: {}", code);
		log.info("===============================================");
	}

	/**
	 * 测试连续发送验证码（应该覆盖之前的验证码）
	 */
	@Test
	void testSendMultipleCodes() {
		String testEmail = "your-email@qq.com";

		log.info("测试连续发送两次验证码");

		// 第一次发送
		emailService.sendVerifyCode(testEmail);
		String firstCode = redisTemplate.opsForValue().get("email:code:" + testEmail);
		log.info("第一次验证码: {}", firstCode);

		// 等待 1 秒
		try {
			Thread.sleep(1000);
		}
		catch (InterruptedException e) {
			e.printStackTrace();
		}

		// 第二次发送
		emailService.sendVerifyCode(testEmail);
		String secondCode = redisTemplate.opsForValue().get("email:code:" + testEmail);
		log.info("第二次验证码: {}", secondCode);

		assertNotNull(secondCode, "第二次发送后应该有新的验证码");
	}

}
