package app

import (
	"github.com/gofiber/fiber/v2"
	"gofiber.study.skcks.cn/common/config"
	"gofiber.study.skcks.cn/common/logger"
	"gofiber.study.skcks.cn/common/utils"
	"gofiber.study.skcks.cn/global"
	"gofiber.study.skcks.cn/middleware"
	"xorm.io/xorm"
)

func reloadDataSources(c *config.BasicConfig) {
	if global.DataSources != nil {
		_ = global.DataSources.Close()
	}

	connGroup, err := xorm.NewEngineGroup("mysql", c.Mysql.DataSources)
	if err != nil {
		logger.Log.Fatalf("[x] [数据源] 致命错误: %s", err)
	}

	utils.MainAppExec(func() {
		logger.Log.Infoln("[√] [数据源] 初始化完成")
	})

	global.DataSources = connGroup

	if c.Mysql.AutoSync && !fiber.IsChild() {
		global.SyncModelToDataSource()
	}

	middleware.NewCasbin(global.DataSources)
}
