package db

import (
	"context"
	"database/sql"
	"time"

	"github.com/pingcap/dbaas/pkg/gormutil"
	"github.com/pingcap/errors"
	"github.com/pingcap/log"
	"github.com/tidbcloud/central-sdk/config"
	"github.com/tidbcloud/central-sdk/migrate"
	"go.uber.org/atomic"
	"gorm.io/gorm"

	_ "github.com/tidbcloud/central-sdk/migrate/central_migrate_record"
)

// globalDB represents the global database connection pool instance and all
// database operation should use db.Transaction interface to retrieve a
// transaction object.
var globalDB *gorm.DB

// initialized prevents the database connection pool being initialized multiple
// times. An error will be returned to the caller if the database has been initialized.
var initialized atomic.Bool

// Initialize initializes the global database connection pool and return error
// if some unexpected errors from the driver and gorm package raised.
func Initialize(cfg config.MysqlConfig, migration bool) (*gorm.DB, error) {
	if initialized.Swap(true) {
		return nil, errors.New("global database is already initialized")
	}

	connCfg := gormutil.Config{
		User:              cfg.User,
		Host:              cfg.Host,
		Database:          cfg.Database,
		Password:          cfg.Password,
		Port:              cfg.Port,
		EnableDetailedLog: config.Global().ServerConfig.EnableDBQueryLog,
		LogLevel:          config.Global().ServerConfig.LogLevel,
	}
	if err := gormutil.EnsureConnectionDatabase(connCfg); err != nil {
		return nil, errors.Trace(err)
	}
	db, err := gormutil.Connect(connCfg)
	if err != nil {
		return nil, errors.Trace(err)
	}
	globalDB = db
	if migration {
		if err := migrate.RunCentralMigrate(globalDB); err != nil {
			return nil, err
		}
	}

	log.Info("Initialize global database successfully")

	return globalDB, nil
}

// Transaction starts a transaction as a block, return error will rollback, otherwise to commit.
func Transaction(fc func(tx *gorm.DB) error, opts ...*sql.TxOptions) (err error) {
	ctx, cancel := context.WithTimeout(context.TODO(), 30*time.Second)
	defer cancel()
	defer func() {
		if r := recover(); r != nil {
			err = errors.Errorf("%v", r)
		}
	}()
	err = globalDB.WithContext(ctx).Transaction(fc, opts...)
	return
}

// Create inserts a new record into the database.
func Create(obj interface{}) error {
	return Transaction(func(tx *gorm.DB) error { return tx.Create(obj).Error })
}

func Delete(value interface{}, conds ...interface{}) error {
	return Transaction(func(tx *gorm.DB) error {
		return tx.Delete(value, conds...).Error
	})
}
