package org.dromara.app.service;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.member.domain.vo.AppUserVo;
import org.dromara.common.core.utils.ip.AddressUtils;
import org.dromara.common.mail.utils.MailUtils;
import org.dromara.member.service.AppUserService;
import org.springframework.stereotype.Service;

/**
 * App登录异地风险检测服务
 * 比对用户上次登录IP归属地与本次登录IP归属地，若发生变化则进行日志与邮件告警。
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AppLoginRiskService {

    private final AppUserService appUserService;

    /**
     * 执行异地登录风险检测
     * @param userId    当前登录用户ID
     * @param currentIp 本次登录IP
     */
    public void checkRisk(Long userId, String currentIp) {
        AppUserVo user = appUserService.queryById(userId);
        if (user == null) {
            return;
        }
        String lastIp = StrUtil.blankToDefault(user.getLoginIp(), "");
        String lastRegion = AddressUtils.getRealAddressByIP(lastIp);
        String currentRegion = AddressUtils.getRealAddressByIP(currentIp);
        boolean validLast = !AddressUtils.UNKNOWN_IP.equals(lastRegion) && !AddressUtils.UNKNOWN_ADDRESS.equals(lastRegion);
        boolean validCurrent = !AddressUtils.UNKNOWN_IP.equals(currentRegion) && !AddressUtils.UNKNOWN_ADDRESS.equals(currentRegion);
        boolean isLocal = AddressUtils.LOCAL_ADDRESS.equals(lastRegion) || AddressUtils.LOCAL_ADDRESS.equals(currentRegion);
        if (validLast && validCurrent && !isLocal && !StrUtil.equals(lastRegion, currentRegion)) {
            log.warn("App用户 {} 异地登录风险, 上次:{}({}), 本次:{}({})", userId, lastRegion, lastIp, currentRegion, currentIp);
            String email = user.getEmail();
            if (StrUtil.isNotBlank(email)) {
                String subject = "异地登录告警";
                String content = "您的账号检测到异地登录风险\n上次登录: " + lastRegion + " (" + lastIp + ")\n本次登录: " + currentRegion + " (" + currentIp + ")";
                try {
                    MailUtils.sendText(email, subject, content);
                } catch (Exception e) {
                    log.error("发送异地登录告警邮件失败: {}", e.getMessage());
                }
            }
        }
    }
}
