package data

import (
	"encoding/json"
	"errors"

	"kra/internal/biz"

	"gorm.io/gorm"
)

func ensureCommunicationIntegrationConfigs(db *gorm.DB) error {
	defaults := []struct {
		kind     string
		provider string
	}{
		{kind: biz.IntegrationKindMQ, provider: "emqx"},
		{kind: biz.IntegrationKindMQ, provider: "rabbitmq"},
		{kind: biz.IntegrationKindWebSocket, provider: "melody"},
	}
	for _, item := range defaults {
		var row integrationConfigPO
		err := db.Where("kind = ? AND provider = ?", item.kind, item.provider).First(&row).Error
		if errors.Is(err, gorm.ErrRecordNotFound) {
			values, marshalErr := json.Marshal(biz.DefaultIntegrationConfig(item.kind, item.provider))
			if marshalErr != nil {
				return marshalErr
			}
			if err = db.Create(&integrationConfigPO{Kind: item.kind, Provider: item.provider, Enabled: false, Config: string(values)}).Error; err != nil {
				return err
			}
			continue
		}
		if err != nil {
			return err
		}
	}
	return nil
}
