package tech.easyflow.auth.config;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import tech.easyflow.common.web.exceptions.BusinessException;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Component
public class DevLoginGuard {

    private final LoginProperties properties;

    public DevLoginGuard(LoginProperties properties) {
        this.properties = properties;
    }

    public void checkAccess(HttpServletRequest request, String account) {
        if (!isAllowedAccount(account)) {
            throw new BusinessException("仅允许使用 admin 账号进行开发免登");
        }
        if (properties.getDevBypass().isLoopbackOnly() && !isLoopbackRequest(request)) {
            throw new BusinessException("开发免登仅允许本机访问");
        }
    }

    boolean isAllowedAccount(String account) {
        return StringUtils.hasText(account)
                && account.equals(properties.getDevBypass().getAccount());
    }

    boolean isLoopbackRequest(HttpServletRequest request) {
        return request != null && isLoopbackAddress(request.getRemoteAddr());
    }

    boolean isLoopbackAddress(String remoteAddr) {
        if (!StringUtils.hasText(remoteAddr)) {
            return false;
        }
        try {
            return InetAddress.getByName(remoteAddr).isLoopbackAddress();
        } catch (UnknownHostException ex) {
            return false;
        }
    }
}
