package storage

import (
	"database/sql"
	"fmt"
	"log"
	"os"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

// DBConfig 数据库配置
type DBConfig struct {
	Host     string
	Port     int
	User     string
	Password string
	Database string
}

var db *sql.DB

// InitDB 初始化数据库连接
func InitDB(config DBConfig) error {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		config.User, config.Password, config.Host, config.Port, config.Database)

	var err error
	db, err = sql.Open("mysql", dsn)
	if err != nil {
		return fmt.Errorf("failed to open database: %v", err)
	}

	// 配置连接池
	db.SetMaxOpenConns(25)
	db.SetMaxIdleConns(5)
	db.SetConnMaxLifetime(5 * time.Minute)

	// 测试连接
	if err := db.Ping(); err != nil {
		return fmt.Errorf("failed to ping database: %v", err)
	}

	log.Println("✅ Database connection established")
	return nil
}

// GetDB 获取数据库连接
func GetDB() *sql.DB {
	return db
}

// CloseDB 关闭数据库连接
func CloseDB() error {
	if db != nil {
		return db.Close()
	}
	return nil
}

// GetDBConfigFromEnv 从环境变量获取数据库配置
func GetDBConfigFromEnv() DBConfig {
	config := DBConfig{
		Host:     "localhost",
		Port:     3306,
		User:     "root",
		Password: "",
		Database: "crm_db",
	}

	if host := os.Getenv("DB_HOST"); host != "" {
		config.Host = host
	}
	if user := os.Getenv("DB_USER"); user != "" {
		config.User = user
	}
	if pwd := os.Getenv("DB_PASSWORD"); pwd != "" {
		config.Password = pwd
	}
	if dbName := os.Getenv("DB_NAME"); dbName != "" {
		config.Database = dbName
	}
	if port := os.Getenv("DB_PORT"); port != "" {
		fmt.Sscanf(port, "%d", &config.Port)
	}

	return config
}
