package mongo

import (
	"context"

	"github.com/tech/sendico/pkg/db/transaction"
	"go.mongodb.org/mongo-driver/v2/mongo"
)

type mongoTransactionFactory struct {
	client *mongo.Client
}

func (f *mongoTransactionFactory) CreateTransaction() transaction.Transaction {
	return &mongoTransaction{client: f.client}
}

type mongoTransaction struct {
	client *mongo.Client
}

func (t *mongoTransaction) Execute(ctx context.Context, cb transaction.Callback) (any, error) {
	session, err := t.client.StartSession()
	if err != nil {
		return nil, err
	}
	defer session.EndSession(ctx)

	run := func(sessCtx context.Context) (any, error) {
		return cb(sessCtx)
	}

	return session.WithTransaction(ctx, run)
}

func newMongoTransactionFactory(client *mongo.Client) transaction.Factory {
	return &mongoTransactionFactory{client: client}
}
