package bridge

import (
	"context"
	"fmt"
)

type Aggregator struct {
	providers []Provider
}

func NewAggregator(cfg *Config) *Aggregator {
	if cfg == nil {
		cfg = DefaultConfig()
	}
	return &Aggregator{
		providers: []Provider{
			NewLiFiProvider(cfg), NewSocketProvider(), NewSquidProvider(cfg),
			NewSymbiosisProvider(), NewRelayProvider(), NewStargateProvider(),
			NewCCIPProvider(cfg), NewHopProvider(),
		},
	}
}

func (a *Aggregator) GetBestQuote(ctx context.Context, req *BridgeRequest) (*BridgeQuote, error) {
	var bestQuote *BridgeQuote
	var bestAmount string
	for _, provider := range a.providers {
		if !provider.SupportsRoute(req.FromChain, req.ToChain) {
			continue
		}
		quote, err := provider.GetQuote(ctx, req)
		if err != nil {
			continue
		}
		if bestQuote == nil || quote.ToAmount > bestAmount {
			bestQuote = quote
			bestAmount = quote.ToAmount
		}
	}
	if bestQuote == nil {
		return nil, fmt.Errorf("no bridge quotes available")
	}
	return bestQuote, nil
}
