package market

import (
	"strconv"
	"strings"
	"time"

	"github.com/tech/sendico/fx/ingestor/internal/market/binance"
	"github.com/tech/sendico/fx/ingestor/internal/market/cbr"
	"github.com/tech/sendico/fx/ingestor/internal/market/coingecko"
	mmodel "github.com/tech/sendico/fx/ingestor/internal/model"
	"github.com/tech/sendico/pkg/merrors"
	"github.com/tech/sendico/pkg/mlogger"
	"github.com/tech/sendico/pkg/model"
)

type ConnectorFactory func(logger mlogger.Logger, settings model.SettingsT) (mmodel.Connector, error)

func BuildConnectors(logger mlogger.Logger, configs []model.DriverConfig[mmodel.Driver]) (map[mmodel.Driver]mmodel.Connector, error) {
	connectors := make(map[mmodel.Driver]mmodel.Connector, len(configs))

	for _, cfg := range configs {
		driver := mmodel.NormalizeDriver(cfg.Driver)
		if driver.IsEmpty() {
			return nil, merrors.InvalidArgument("market: connector driver is empty", "driver")
		}

		var (
			conn mmodel.Connector
			err  error
		)

		switch driver {
		case mmodel.DriverBinance:
			conn, err = binance.NewConnector(logger, cfg.Settings)
		case mmodel.DriverCoinGecko:
			conn, err = coingecko.NewConnector(logger, cfg.Settings)
		case mmodel.DriverCBR:
			conn, err = cbr.NewConnector(logger, cfg.Settings)
		default:
			err = merrors.InvalidArgument("market: unsupported driver "+driver.String(), "driver")
		}

		if err != nil {
			return nil, merrors.InternalWrap(err, "market: build connector "+driver.String())
		}
		connectors[driver] = conn
	}

	return connectors, nil
}

func BuildRateReference(provider, symbol string, now time.Time) string {
	if strings.TrimSpace(provider) == "" {
		provider = "unknown"
	}
	return provider + ":" + symbol + ":" + strconv.FormatInt(now.UnixMilli(), 10)
}
