package db

import (
	"fmt"
	"log"
	"log/slog"

	"git.ma-al.com/goc_daniel/b2b/app/config"

	extraClausePlugin "github.com/WinterYukky/gorm-extra-clause-plugin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB

func init() {
	if DB == nil {
		dbconn, err := newMySQLDB(&config.Get().Database)
		if err != nil {
			slog.Error("⚠️ No connection to database was possible to establish", "error", err.Error())
		}
		DB = dbconn
	}
}

func Get() *gorm.DB {
	return DB
}

// newMySQLDB creates a new MariaDB/MySQL database connection
func newMySQLDB(cfg *config.DatabaseConfig) (*gorm.DB, error) {

	dsn := cfg.GetDSN()

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Error),
	})

	if err != nil {
		return nil, fmt.Errorf("failed to connect to database: %w", err)
	}

	sqlDB, err := db.DB()
	if err != nil {
		return nil, fmt.Errorf("failed to get database instance: %w", err)
	}

	// Connection pool settings
	sqlDB.SetMaxIdleConns(cfg.MaxIdleConns)
	sqlDB.SetMaxOpenConns(cfg.MaxOpenConns)
	sqlDB.SetConnMaxLifetime(cfg.ConnMaxLifetime)

	log.Println("✓ Database connection established successfully")
	err = db.Use(extraClausePlugin.New())
	if err != nil {
		panic(err)
	}
	return db, nil
}

// // RunMigrations runs all database migrations
// func RunMigrations() error {
// 	if DB == nil {
// 		return fmt.Errorf("database connection not established")
// 	}

// 	log.Println("Running database migrations...")

// 	// Add your models here for AutoMigrate
// 	// Example: err := db.AutoMigrate(&model.Customer{})

// 	err := DB.AutoMigrate(&model.Customer{})
// 	if err != nil {
// 		return fmt.Errorf("failed to run migrations: %w", err)
// 	}

// 	log.Println("✓ Database migrations completed successfully")

// 	return nil
// }

// // SeedAdminUser creates a default admin user if one doesn't exist
// // Call this function with admin credentials after migrations
// func SeedAdminUser(adminEmail, adminPassword string) error {
// 	log.Println("✓ Admin seeding ready - implement with your User model")

// 	// Example implementation when you have a User model:
// 	// var count int64
// 	// db.Model(&model.User{}).Where("role = ?", "admin").Count(&count)
// 	// if count > 0 {
// 	// 	log.Println("✓ Admin user already exists")
// 	// 	return nil
// 	// }
// 	// hashedPassword, err := bcrypt.GenerateFromPassword([]byte(adminPassword), bcrypt.DefaultCost)
// 	// if err != nil {
// 	// 	return fmt.Errorf("failed to hash password: %w", err)
// 	// }
// 	// admin := model.User{
// 	// 	Email:    adminEmail,
// 	// 	Password: string(hashedPassword),
// 	// 	Role:    "admin",
// 	// 	IsActive: true,
// 	// }
// 	// if err := db.Create(&admin).Error; err != nil {
// 	// 	return err
// 	// }
// 	// log.Printf("✓ Created admin user: %s", adminEmail)

// 	// Suppress unused variable warning
// 	_, _ = bcrypt.GenerateFromPassword([]byte(adminPassword), bcrypt.DefaultCost)

// 	return nil
// }
