package db

import (
	"context"
	"database/sql"

	"github.com/pingcap/errors"
	"github.com/tidbcloud/core-portal/internal/central/config"
	"github.com/tidbcloud/core-portal/internal/central/pkg/gormutil"
	"github.com/tidbcloud/pkgv2/log"
	"go.uber.org/atomic"
	"gorm.io/gorm"
)

type Provider interface {
	ReadDB(ctx context.Context) *gorm.DB
	WriteDB(ctx context.Context) *gorm.DB
}

// Transactioner provide the ability to start a transaction
type Transactioner interface {
	Transaction(ctx context.Context, cb func(ctx context.Context) error) error
}

// TransProvider provide DB handle and the transaction
type TransProvider interface {
	Provider
	Transactioner
}

// 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

// for test only.
func ResetInitialize() {
	initialized.Swap(false)
}

// InitializeWithoutMigrate initializes the global database connection pool and return error
// if some unexpected errors from the driver and gorm package raised.
func InitializeWithoutMigrate(cfg config.MysqlConfig) (*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

	log.Info(context.TODO(), "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(), config.DefaultDBOperationTimeout)
	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
	})
}
