package mongo

import (
	"context"
	"time"

	"github.com/tech/sendico/fx/storage"
	"github.com/tech/sendico/fx/storage/mongo/store"
	"github.com/tech/sendico/pkg/db"
	"github.com/tech/sendico/pkg/db/transaction"
	"github.com/tech/sendico/pkg/merrors"
	"github.com/tech/sendico/pkg/mlogger"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.uber.org/zap"
)

type Store struct {
	logger    mlogger.Logger
	conn      *db.MongoConnection
	db        *mongo.Database
	txFactory transaction.Factory

	rates      storage.RatesStore
	quotes     storage.QuotesStore
	pairs      storage.PairStore
	currencies storage.CurrencyStore
}

func New(logger mlogger.Logger, conn *db.MongoConnection) (*Store, error) {
	if conn == nil {
		return nil, merrors.InvalidArgument("mongo connection is nil")
	}

	client := conn.Client()
	if client == nil {
		return nil, merrors.Internal("mongo client not initialised")
	}

	db := conn.Database()
	txFactory := newMongoTransactionFactory(client)

	s := &Store{
		logger:    logger.Named("storage").Named("mongo"),
		conn:      conn,
		db:        db,
		txFactory: txFactory,
	}

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := s.Ping(ctx); err != nil {
		s.logger.Error("Mongo ping failed during store init", zap.Error(err))
		return nil, err
	}

	ratesStore, err := store.NewRates(s.logger, db)
	if err != nil {
		s.logger.Error("Failed to initialize rates store", zap.Error(err))
		return nil, err
	}
	quotesStore, err := store.NewQuotes(s.logger, db, txFactory)
	if err != nil {
		s.logger.Error("Failed to initialize quotes store", zap.Error(err))
		return nil, err
	}
	pairsStore, err := store.NewPair(s.logger, db)
	if err != nil {
		s.logger.Error("Failed to initialize pair store", zap.Error(err))
		return nil, err
	}
	currencyStore, err := store.NewCurrency(s.logger, db)
	if err != nil {
		s.logger.Error("Failed to initialize currency store", zap.Error(err))
		return nil, err
	}

	s.rates = ratesStore
	s.quotes = quotesStore
	s.pairs = pairsStore
	s.currencies = currencyStore

	s.logger.Info("Mongo storage ready")
	return s, nil
}

func (s *Store) Ping(ctx context.Context) error {
	return s.conn.Ping(ctx)
}

func (s *Store) Rates() storage.RatesStore {
	return s.rates
}

func (s *Store) Quotes() storage.QuotesStore {
	return s.quotes
}

func (s *Store) Pairs() storage.PairStore {
	return s.pairs
}

func (s *Store) Currencies() storage.CurrencyStore {
	return s.currencies
}

func (s *Store) Database() *mongo.Database {
	return s.db
}

func (s *Store) TransactionFactory() transaction.Factory {
	return s.txFactory
}

var _ storage.Repository = (*Store)(nil)
