package dualtrx_helper

import (
	dg "github.com/karincake/apem/db-gorm-pg"
	"gorm.io/gorm"
)

type Dualtx struct {
	Sync   *gorm.DB
	Simgos *gorm.DB
}

func NewDualtx() *Dualtx {
	return &Dualtx{
		Sync:   dg.I.Begin(),
		Simgos: dg.IS["simrs"].Begin(),
	}
}

func NewTx() *Dualtx {
	return &Dualtx{
		Sync:   dg.I,
		Simgos: dg.IS["simrs"],
	}
}

func (t *Dualtx) Commit() error {
	if err := t.Sync.Commit().Error; err != nil {
		return err
	}

	if err := t.Simgos.Commit().Error; err != nil {
		return err
	}
	return nil
}

func (t *Dualtx) Rollback() {
	t.Sync.Rollback()
	t.Simgos.Rollback()
}

type DualTxFunc func(tx *Dualtx) error

func WithDualTx(fn DualTxFunc) error {
	var (
		tx  = NewDualtx()
		err error
	)

	defer func() {
		if err != nil {
			tx.Rollback()
		}
	}()

	if err = fn(tx); err != nil {
		return err
	}

	if err = tx.Commit(); err != nil {
		return err
	}

	return nil
}
