package database

import (
	"github.com/mitchellh/mapstructure"
	"matrix-common/pkg/logger"
	"matrix-middle-service/internel/controller/record/location/dto"
	"matrix-middle-service/pkg/config/database"
	"matrix-middle-service/pkg/database/model"
)

var SupportDataSources = make(map[string]InitDSFn)
var drivers []DataBase

type InitDSFn = func(conf database.DataSourcesType[any]) DataBase

type DataBase interface {
	Open() error
	Close() error

	GetAllBotTypes() ([]*model.BotType, error)
	AddBotType(bt *model.BotType) error
	DeleteBotTypeById(id string) error

	RecordLocation(record *model.LocationRecord) error
	GetLocationRecord(record *dto.GetDto) ([]*model.LocationRecord, error)
}

func Init(conf []interface{}) {
	drivers = make([]DataBase, 0, len(SupportDataSources))

	logger.Log().Debug("[数据源] 初始化")
	for _, item := range conf {
		dst := database.DataSourcesType[any]{}
		_ = mapstructure.Decode(item, &dst)

		fn, ok := SupportDataSources[dst.Type]
		if !ok {
			logger.Log().Fatalf("不支持的数据源类型 %s", dst.Type)
		}

		if !dst.Enable {
			continue
		}

		drivers = append(drivers, fn(dst))
	}
}

func Register(name string, fn InitDSFn) {
	SupportDataSources[name] = fn
}

func Open() (err error) {
	for _, driver := range drivers {
		err = driver.Open()
		if err != nil {
			return
		}
	}
	return
}

func Exec(fn func(db DataBase) error) error {
	if len(drivers) > 0 {
		return fn(drivers[0])
	} else {
		logger.Log().Error("[database] 没有可用的数据源")
	}
	return nil
}

func ExecMulti(fn func(db DataBase) error) error {
	if len(drivers) == 0 {
		logger.Log().Error("[database] 没有可用的数据源")
	}

	for _, driver := range drivers {
		err := fn(driver)
		if err != nil {
			return err
		}
	}
	return nil
}

func Close() {
	for _, driver := range drivers {
		_ = driver.Close()
	}
	return
}
