package utils

import (
	"errors"
	"fmt"
	"io"
	"log/slog"
	"net"
	"syscall"
)

func WarpConnErr(err error) (bool, error) {
	if err == nil {
		return true, nil
	}

	var opErr *net.OpError
	switch {

	case errors.Is(err, net.ErrClosed):
		slog.Debug("连接已关闭")
		return false, nil

	case errors.Is(err, io.EOF):
		slog.Debug("连接被对端关闭")
		return false, nil

	case errors.As(err, &opErr):
		switch {
		case
			errors.Is(opErr.Err, syscall.WSAECONNRESET), errors.Is(opErr.Err, syscall.WSAECONNABORTED),
			errors.Is(opErr.Err, syscall.ECONNRESET), errors.Is(opErr.Err, syscall.ECONNABORTED):
			slog.Debug("连接被对端重置")
			return false, nil
		case opErr.Timeout():
			slog.Debug("连接已超时")
			return false, nil
		}
	}
	return false, fmt.Errorf("连接发生未处理的错误: %w", err)
}
