package mongo

import (
	"context"
	"time"

	"github.com/tech/sendico/gateway/aurora/storage"
	"github.com/tech/sendico/gateway/aurora/storage/mongo/store"
	gatewayoutbox "github.com/tech/sendico/gateway/common/outbox"
	"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 Repository struct {
	logger    mlogger.Logger
	conn      *db.MongoConnection
	db        *mongo.Database
	txFactory transaction.Factory

	payouts storage.PayoutsStore
	outbox  gatewayoutbox.Store
}

func New(logger mlogger.Logger, conn *db.MongoConnection) (*Repository, error) {
	if logger == nil {
		logger = zap.NewNop()
	}
	if conn == nil {
		return nil, merrors.InvalidArgument("mongo connection is nil")
	}
	client := conn.Client()
	if client == nil {
		return nil, merrors.Internal("mongo client is not initialised")
	}
	db := conn.Database()
	if db == nil {
		return nil, merrors.Internal("mongo database is not initialised")
	}
	dbName := db.Name()
	logger = logger.Named("storage").Named("mongo")
	if dbName != "" {
		logger = logger.With(zap.String("database", dbName))
	}
	result := &Repository{
		logger:    logger,
		conn:      conn,
		db:        db,
		txFactory: newMongoTransactionFactory(client),
	}
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := result.conn.Ping(ctx); err != nil {
		result.logger.Error("Mongo ping failed during repository initialisation", zap.Error(err))
		return nil, err
	}
	payoutsStore, err := store.NewPayouts(result.logger, result.db)
	if err != nil {
		result.logger.Error("Failed to initialise payouts store", zap.Error(err), zap.String("store", "payments"))
		return nil, err
	}
	outboxStore, err := gatewayoutbox.NewMongoStore(result.logger, result.db)
	if err != nil {
		result.logger.Error("Failed to initialise outbox store", zap.Error(err), zap.String("store", "outbox"))
		return nil, err
	}
	result.payouts = payoutsStore
	result.outbox = outboxStore
	result.logger.Info("Payouts gateway MongoDB storage initialised")
	return result, nil
}

func (r *Repository) Payouts() storage.PayoutsStore {
	return r.payouts
}

func (r *Repository) Outbox() gatewayoutbox.Store {
	return r.outbox
}

func (r *Repository) TransactionFactory() transaction.Factory {
	return r.txFactory
}

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