package proxy_pool

import (
	"context"
	"fmt"
	"time"

	"kami/internal/model"

	"github.com/gogf/gf/v2/net/gclient"
)

const (
	DefaultValidateURL     = "https://www.baidu.com"
	DefaultValidateTimeout = 10 * time.Second
	MaxRetryTimes          = 3
)

type ProxyValidator struct {
	validateURL     string
	validateTimeout time.Duration
}

func NewProxyValidator() *ProxyValidator {
	return &ProxyValidator{
		validateURL:     DefaultValidateURL,
		validateTimeout: DefaultValidateTimeout,
	}
}

func (v *ProxyValidator) ValidateProxy(ctx context.Context, proxy *model.ProxyInfo) bool {
	if proxy == nil {
		return false
	}

	client := gclient.New()
	client.SetTimeout(v.validateTimeout)

	proxyURL := proxy.String()
	client.SetProxy(proxyURL)

	resp, err := client.Get(ctx, v.validateURL)
	if err != nil {
		return false
	}
	defer resp.Close()

	return resp.StatusCode == 200
}

func (v *ProxyValidator) GetValidProxy(ctx context.Context, fetchFunc func(context.Context) (*model.ProxyInfo, error)) (*model.ProxyInfo, error) {
	for range MaxRetryTimes {
		proxy, err := fetchFunc(ctx)
		if err != nil {
			continue
		}

		if v.ValidateProxy(ctx, proxy) {
			return proxy, nil
		}
	}

	return nil, fmt.Errorf("获取有效代理失败，已重试 %d 次", MaxRetryTimes)
}

func (v *ProxyValidator) SetValidateURL(validateURL string) {
	if validateURL != "" {
		v.validateURL = validateURL
	}
}

func (v *ProxyValidator) SetValidateTimeout(timeout time.Duration) {
	if timeout > 0 {
		v.validateTimeout = timeout
	}
}
