package data

import (
	"testing"
	"time"

	"kra/app/system/internal/conf"

	"google.golang.org/protobuf/types/known/durationpb"
)

func TestWebSocketIntegrationConfigRoundTrip(t *testing.T) {
	db := openIntegrationConfigTestDB(t)
	want := &conf.AdminBackend_WebSocket{
		Enabled: true, Path: "/events", AllowOrigins: []string{"https://admin.example.com"},
		MaxMessageSize: 4096, WriteWait: durationpb.New(3 * time.Second),
		PongWait: durationpb.New(20 * time.Second), PingPeriod: durationpb.New(15 * time.Second),
		MessageBufferSize: 32, ConcurrentMessageHandling: true,
	}
	if err := saveWebSocketIntegrationConfig(db, want); err != nil {
		t.Fatal(err)
	}
	got, found, err := loadWebSocketIntegrationConfig(db)
	if err != nil {
		t.Fatal(err)
	}
	if !found {
		t.Fatal("websocket integration configuration was not found")
	}
	if !got.Enabled || got.Path != want.Path || got.MaxMessageSize != want.MaxMessageSize || got.MessageBufferSize != want.MessageBufferSize {
		t.Fatalf("loaded websocket config = %#v", got)
	}
	if len(got.AllowOrigins) != 1 || got.AllowOrigins[0] != want.AllowOrigins[0] {
		t.Fatalf("allow origins = %v", got.AllowOrigins)
	}
}

func TestResolveWebSocketIntegrationConfigPrefersDatabase(t *testing.T) {
	db := openIntegrationConfigTestDB(t)
	if err := saveWebSocketIntegrationConfig(db, &conf.AdminBackend_WebSocket{Enabled: true, Path: "/database"}); err != nil {
		t.Fatal(err)
	}
	got, err := resolveWebSocketIntegrationConfig(db, &conf.AdminBackend_WebSocket{Path: "/legacy"})
	if err != nil {
		t.Fatal(err)
	}
	if got.Path != "/database" || !got.Enabled {
		t.Fatalf("resolved websocket config = %#v", got)
	}
}
