package database

import (
	"fmt"
	"log"
	"os"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// DBConfig holds MySQL connection parameters.
type DBConfig struct {
	Host     string
	Port     string
	User     string
	Password string
	DBName   string
}

func (c DBConfig) DSN() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		c.User, c.Password, c.Host, c.Port, c.DBName)
}

func devConfig() DBConfig {
	return DBConfig{
		Host:     "10.1.1.100",
		Port:     "3306",
		User:     "sproutgate-test",
		Password: "sproutgate-test",
		DBName:   "sproutgate-test",
	}
}

func prodConfig() DBConfig {
	return DBConfig{
		Host:     "192.168.1.100",
		Port:     "3306",
		User:     "sproutgate",
		Password: "sproutgate",
		DBName:   "sproutgate",
	}
}

// Open 根据环境变量打开数据库连接。
// 优先级：DB_DSN > APP_ENV(production/prod -> 生产库) > 默认开发库
func Open() (*gorm.DB, error) {
	dsn := os.Getenv("DB_DSN")
	if dsn == "" {
		env := os.Getenv("APP_ENV")
		if env == "production" || env == "prod" {
			dsn = prodConfig().DSN()
			log.Println("[database] 使用生产数据库 192.168.1.100:3306/sproutgate")
		} else {
			dsn = devConfig().DSN()
			log.Println("[database] 使用开发数据库 10.1.1.100:3306/sproutgate-test")
		}
	} else {
		log.Println("[database] 使用自定义 DB_DSN")
	}

	logLevel := logger.Info
	if os.Getenv("GIN_MODE") == "release" {
		logLevel = logger.Warn
	}

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logLevel),
	})
	if err != nil {
		return nil, fmt.Errorf("连接数据库失败: %w", err)
	}

	sqlDB, err := db.DB()
	if err != nil {
		return nil, err
	}
	sqlDB.SetMaxOpenConns(25)
	sqlDB.SetMaxIdleConns(5)

	return db, nil
}
