package data

import (
	"errors"

	"kra/internal/integration/runtimeconfig"

	"gorm.io/gorm"
)

func readIntegrationRuntime(db *gorm.DB) ([]runtimeconfig.Config, error) {
	if db == nil || !db.Migrator().HasTable(&integrationConfigPO{}) {
		return nil, nil
	}
	var rows []integrationConfigPO
	if err := db.Session(&gorm.Session{NewDB: true}).
		Where("kind IN ?", []string{"mq", "websocket"}).
		Order("kind ASC, provider ASC").
		Find(&rows).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, err
	}
	configs := make([]runtimeconfig.Config, 0, len(rows))
	for _, row := range rows {
		configs = append(configs, runtimeconfig.Config{Kind: row.Kind, Provider: row.Provider, Enabled: row.Enabled, Values: []byte(row.Config)})
	}
	return configs, nil
}

func (d *Data) loadIntegrationRuntime(db *gorm.DB) error {
	configs, err := readIntegrationRuntime(db)
	if err != nil {
		return err
	}
	if d.integrations != nil {
		d.integrations.Replace(configs)
	}
	return nil
}
