package websocket

import (
	"context"
	"encoding/json"
	"testing"
	"time"
)

func TestConfigCompletesLocalTemporaryHandshake(t *testing.T) {
	tests := []struct {
		name   string
		values map[string]any
	}{
		{
			name: "default origin policy",
			values: map[string]any{
				"path":             "/connection-test",
				"write_wait":       "1s",
				"pong_wait":        "2s",
				"ping_period":      "1s",
				"max_message_size": 1024,
			},
		},
		{
			name: "configured origin",
			values: map[string]any{
				"path":          "/origin-test",
				"allow_origins": []string{"https://admin.example.test"},
				"write_wait":    "1s",
				"pong_wait":     "2s",
				"ping_period":   "1s",
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			raw, err := json.Marshal(tt.values)
			if err != nil {
				t.Fatalf("json.Marshal() error = %v", err)
			}
			ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
			defer cancel()

			if err = TestConfig(ctx, raw); err != nil {
				t.Fatalf("TestConfig() error = %v", err)
			}
		})
	}
}

func TestConfigHonorsCanceledContextWithoutExternalAccess(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	cancel()

	err := TestConfig(ctx, json.RawMessage(`{"path":"/connection-test"}`))
	if err != context.Canceled {
		t.Fatalf("TestConfig() error = %v, want context.Canceled", err)
	}
}
