package route

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http/httptest"
	"reflect"
	"strings"
	"sync"
	"testing"
)

type testJSONBodyModel struct {
	Labels map[string]string `json:"labels"`
}

func TestSchemaValidateJSONBody(t *testing.T) {
	t.Run("valid JSON leaves the model unchanged and rewrites the body", func(t *testing.T) {
		model := &testJSONBodyModel{Labels: map[string]string{"original": "value"}}
		wantModel := &testJSONBodyModel{Labels: map[string]string{"original": "value"}}
		schema := &Schema{
			PathRegex:     "^/test$",
			JSONBodyModel: model,
		}

		const body = `{"labels":{"request":"value"}}`
		request := httptest.NewRequest("POST", "/test", strings.NewReader(body))
		if err := schema.Validate(request); err != nil {
			t.Fatalf("Validate() error = %v", err)
		}

		if !reflect.DeepEqual(model, wantModel) {
			t.Fatalf("JSONBodyModel was modified: got %#v, want %#v", model, wantModel)
		}
		rewrittenBody, err := io.ReadAll(request.Body)
		if err != nil {
			t.Fatalf("read rewritten request body: %v", err)
		}
		if string(rewrittenBody) != body {
			t.Fatalf("rewritten request body = %q, want %q", rewrittenBody, body)
		}
	})

	t.Run("invalid JSON is rejected", func(t *testing.T) {
		schema := &Schema{
			PathRegex:     "^/test$",
			JSONBodyModel: &testJSONBodyModel{},
		}
		const body = `{"labels":`
		request := httptest.NewRequest("POST", "/test", strings.NewReader(body))

		err := schema.Validate(request)
		if err == nil {
			t.Fatal("Validate() error = nil, want invalid JSON error")
		}
		var decoded interface{}
		decodeErr := json.Unmarshal([]byte(body), &decoded)
		wantErr := fmt.Sprintf("unable to unmarshal the request body %s: %v", body, decodeErr)
		if err.Error() != wantErr {
			t.Fatalf("Validate() error = %q, want %q", err, wantErr)
		}
	})
}

func TestSchemaValidateJSONBodyConcurrently(t *testing.T) {
	schema := &Schema{
		PathRegex:     "^/test$",
		JSONBodyModel: &testJSONBodyModel{},
	}

	const requestCount = 100
	var wg sync.WaitGroup
	errors := make(chan error, requestCount)
	for range requestCount {
		wg.Add(1)
		go func() {
			defer wg.Done()
			request := httptest.NewRequest("POST", "/test", strings.NewReader(`{"labels":{"key":"value"}}`))
			errors <- schema.Validate(request)
		}()
	}
	wg.Wait()
	close(errors)

	for err := range errors {
		if err != nil {
			t.Errorf("Validate() error = %v", err)
		}
	}
}
