package transactionimp

import (
	"context"

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

type MongoTransaction struct {
	client *mongo.Client
}

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

	callback := func(c context.Context) (any, error) {
		return cb(c)
	}

	return session.WithTransaction(ctx, callback)
}

func Create(client *mongo.Client) *MongoTransaction {
	return &MongoTransaction{client: client}
}
