package proxy_pool

import (
	"context"
	"time"

	"kami/internal/model"

	"github.com/gogf/gf/v2/errors/gerror"
)

var defaultStrategy model.IProxyPoolStrategy

func (s *sProxyPool) InitStrategy(ctx context.Context, apiURL string, ttl time.Duration) error {
	if apiURL == "" {
		return gerror.New("代理池API地址不能为空")
	}

	defaultStrategy = NewMinuteExpireStrategy(apiURL, ttl)
	return nil
}

func (s *sProxyPool) InitActiveExpireStrategy(ctx context.Context, apiURL string, ttl time.Duration, refreshThreshold time.Duration) error {
	if apiURL == "" {
		return gerror.New("代理池API地址不能为空")
	}

	defaultStrategy = NewActiveExpireStrategy(apiURL, ttl, refreshThreshold)
	return nil
}

func (s *sProxyPool) GetProxyByOrderId(ctx context.Context, orderId string) (*model.ProxyInfo, error) {
	if defaultStrategy == nil {
		return nil, gerror.New("代理池未初始化")
	}

	return defaultStrategy.GetProxy(ctx, orderId)
}

func (s *sProxyPool) SetProxyForOrder(ctx context.Context, orderId string, proxy *model.ProxyInfo) error {
	if defaultStrategy == nil {
		return gerror.New("代理池未初始化")
	}

	return defaultStrategy.SetProxy(ctx, orderId, proxy)
}

func (s *sProxyPool) RemoveProxyForOrder(ctx context.Context, orderId string) error {
	if defaultStrategy == nil {
		return gerror.New("代理池未初始化")
	}

	return defaultStrategy.RemoveProxy(ctx, orderId)
}

func (s *sProxyPool) GetProxyTTL(ctx context.Context, orderId string) (time.Duration, error) {
	if defaultStrategy == nil {
		return 0, gerror.New("代理池未初始化")
	}

	return defaultStrategy.GetTTL(ctx, orderId)
}

func (s *sProxyPool) SwitchStrategy(strategy model.IProxyPoolStrategy) {
	defaultStrategy = strategy
}
