// Package db 数据库连接建立库
package db

import (
	"fmt"
	"log"
	"time"

	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/sql"
	_ "github.com/go-sql-driver/mysql"
	"gitlab.galaxy-immi.com/Backend-group/go-com/nacos"
)

type ClientType interface {
    // example:
	// interface{ *ssm.Client | *rpc.Client | *crm.Client | *flow.Client }
}

type ClientHandler[T ClientType] interface {
	SetClient(c T)
	SetRaw(r *sql.Driver)
}

// ReleaseDB 释放db链接
func ReleaseDB() { }


// getDSN 获取数据库的连接DSN
func getDSN(tableName string, database nacos.Database) string {
	user := database.Username
	pass := database.Pass
	addr := database.Host + ":" + database.Port
	return fmt.Sprintf("%s:%s@tcp(%s)/%s?interpolateParams=true&loc=Local&parseTime=True&timeTruncate=1s", user, pass, addr, tableName)
}

func getDriver(dsn string) *sql.Driver {
	fmt.Println(dsn)

	drv, err := sql.Open(dialect.MySQL, dsn)
	if err != nil {
		log.Fatalf("failed opening connection to mysql with dsn: %v", err)
	}

	db := drv.DB()
	db.SetConnMaxIdleTime(time.Second * 30)
	db.SetConnMaxLifetime(time.Minute)
	db.SetMaxIdleConns(20)
	db.SetMaxOpenConns(20)

	return drv
}
