// Package db 具体的数据库连接渲染模板
package db

import (
	ent "convert-server/domain/entity/serversitemicros"
	"log"

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

// serverSiteMicros serverSiteMicros数据库操作类
type serverSiteMicrosDB struct {
	c *ent.Client
	r *sql.Driver
}

var (
	serverSiteMicrosDb = &serverSiteMicrosDB{}
)

func (r *serverSiteMicrosDB) SetClient(c *ent.Client) {
	r.c = c
}

func (r *serverSiteMicrosDB) SetRaw(raw *sql.Driver) {
	r.r = raw
}

// GetServerSiteMicrosDB 获取 serversitemicros 数据库
func GetServerSiteMicrosDB() *ent.Client {
	return serverSiteMicrosDb.c
}

// GetServerSiteMicrosDBRaw 获取 serversitemicros 原始数据库
func GetServerSiteMicrosDBRaw() *sql.Driver {
	return serverSiteMicrosDb.r
}

func initServerSiteMicrosDB(handler ClientHandler[*ent.Client], tableName string, database nacos.Database) {
	raw, c := openServerSiteMicrosDbWithPool(getDSN(tableName, database), database)

	handler.SetClient(c)
	handler.SetRaw(raw)
}

// openServerSiteMicrosDbWithPool 打开数据库并配置db连接池
func openServerSiteMicrosDbWithPool(dsn string, database nacos.Database) (*sql.Driver, *ent.Client) {
	drv := getDriver(dsn)

	client := ent.NewClient(ent.Driver(&driver.MultiDriver{
		RW:   drv,
		Name: database.DbName,
		User: database.Username,
		Host: database.Host,
	}))

	err := drv.DB().Ping()
	if err != nil {
		log.Fatalf("failed opening connection to mysql: %v", err)
	}

	return drv, client
}

func init() {
	w := nacos.GetConfig()
	initServerSiteMicrosDB(serverSiteMicrosDb, w.ServerSiteMicrosDb.DbName, w.ServerSiteMicrosDb)
}
