package repositories

import (
	"log"

	"gorm.io/gorm"
)

// TransactionManager struct untuk handle manual transaction
type TransactionManager struct {
	db *gorm.DB
}

func NewTransactionManager(db *gorm.DB) *TransactionManager {
	return &TransactionManager{db: db}
}

// Begin memulai transaksi database
func (m *TransactionManager) Begin() *gorm.DB {
	return m.db.Begin()
}

// Rollback membatalkan transaksi jika terjadi error
func (m *TransactionManager) Rollback(tx *gorm.DB) {
	// Rollback hanya jika transaksi belum di-commit/rollback
	if r := recover(); r != nil {
		tx.Rollback()
		log.Printf("⚠️ Transaction panicked: %v", r)
	} else if tx.Error != nil {
        // Jika tx sudah error, rollback
		tx.Rollback()
	} else {
        // Rollback aman
        tx.Rollback()
    }
}

// Commit menyimpan perubahan permanen ke database
func (m *TransactionManager) Commit(tx *gorm.DB) error {
	return tx.Commit().Error
}