package com.qnfhq.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.Setting;
import com.qnfhq.common.exception.RenException;
import com.qnfhq.common.utils.MessageUtils;
import com.qnfhq.common.utils.SpringContextUtils;
import com.qnfhq.modules.user.entity.SettingEntity;
import com.qnfhq.modules.user.enums.SettingEnum;
import com.qnfhq.modules.user.service.SettingService;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 验证邮箱非临时邮箱
 *
 * @Author: Yelz 30262728@qq.com
 * @Date: 2025/11/15 09:21
 * @Description:
 */
public class EmailValidUtils {

    /**
     * 邮箱验证
     */
    public static void validateEmail(String email) {
        //大小写空格检查
        String lowerCaseTrimEmail = email.toLowerCase().replaceAll(" ","");
        if(!lowerCaseTrimEmail.equals(email)) {
            throw new RenException(MessageUtils.message("user.register.email.must.lowerCase"));//请使用小写邮箱并检查空白行
        }
        email=email.trim();
        String domain = extractDomain(email);
        SettingService settingService = SpringContextUtils.getBean(SettingService.class);

        //邮箱白名单
        SettingEntity byId = settingService.getSetting(SettingEnum.EMAIL_WHITE_SET.name());
        String settingValue = byId.getSettingValue();
        Set<String> domains = new HashSet<>(Arrays.asList(settingValue.split(",")));
        if(!domains.contains(domain)){
            throw new RenException(MessageUtils.message("user.register.email.isTemp"));//检测到临时邮箱，请使用常见可信邮箱
        }

    }

    /**
     * 提取邮箱域名
     */
    public static String extractDomain(String email) {
        int atIndex = email.lastIndexOf('@');
        if (atIndex > 0 && atIndex < email.length() - 1) {
            return email.substring(atIndex + 1).toLowerCase();
        }
        return "";
    }


}
