package gormutil

import (
	"context"
	"fmt"

	"github.com/tidbcloud/pkgv2/log"
	"go.uber.org/atomic"
	"gorm.io/gorm"
)

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

func InitializeWithoutMigrate(cfg Config) (*gorm.DB, error) {
	if initialized.Swap(true) {
		return nil, fmt.Errorf("global database is already initialized")
	}

	if err := EnsureConnectionDatabase(cfg); err != nil {
		return nil, fmt.Errorf("ensure connection database: %w", err)
	}
	db, err := Connect(cfg)
	if err != nil {
		return nil, fmt.Errorf("gormutil.Connect: %w", err)
	}

	log.Info(context.TODO(), "Initialize global database successfully")
	return db, nil
}
