package integration

import (
	"errors"

	"kra/internal/integration/runtimeconfig"

	"gorm.io/gorm"
)

// ReadRuntime returns the communication integration snapshot used by the
// long-lived MQ/WebSocket adapters.
func ReadRuntime(db *gorm.DB) ([]runtimeconfig.Config, error) {
	if db == nil || !db.Migrator().HasTable(&ConfigPO{}) {
		return nil, nil
	}
	var rows []ConfigPO
	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
}
