package handler

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/labstack/echo/v4"
	"github.com/stretchr/testify/assert"
	"gopkg.in/yaml.v3"
)

var (
	h *Handler
	e *echo.Echo
)

func TestHandler_ValidateTc(t *testing.T) {
	setup()

	type args struct {
		spec string
	}
	tests := []struct {
		name         string
		args         args
		errorMessage string
	}{
		{
			name: "basic",
			args: args{spec: `
tc:
  pd:
    image: 'pingcap/pd:nightly'
    replicas: 1
    requests:
      storage: 10Gi
      cpu: 250m
      memory: 256Mi
    limits:
      cpu: 4000m
      memory: 8Gi
`},
			errorMessage: "",
		},
		{
			name: "error-case-1",
			args: args{spec: `
tc:
  tidb:
    replicas: 3
    image: 'hub.pingcap.net/qa/tidb:v4.0.14-pre'
    config: |
      [log]
      # Log level: debug, info, warn, error, fatal.
      level = "info"
    requests:
      cpu: 4000m
      memory: 8Gi
    limits:
      cpu: 4000m
      memory: 8Gi
      topologySpreadConstraints:
        - topologyKey: zone
`},
			errorMessage: `{"message":"badrequest: code=400, message=quantities must match the regular expression '^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$', internal=quantities must match the regular expression '^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$'","reason":"BadRequest","code":400}`,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var c map[string]interface{}
			mustUnmarshalYaml([]byte(tt.args.spec), &c)
			b, err := json.Marshal(c)
			assert.NoError(t, err)

			req := httptest.NewRequest(echo.POST, "/api/v1/validate", bytes.NewReader(b))
			req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
			rec := httptest.NewRecorder()
			assert.Nil(t, h.ValidateTc(e.NewContext(req, rec)))
			if tt.errorMessage == "" {
				assert.Equal(t, http.StatusOK, rec.Code)
			} else {
				assert.Equal(t, tt.errorMessage, strings.TrimSpace(rec.Body.String()))
			}
		})
	}
}

func setup() {
	h = NewHandler()
	e = NewHTTPServer(h)
}

func mustUnmarshalYaml(b []byte, o interface{}) {
	if err := yaml.Unmarshal(b, o); err != nil {
		panic(err)
	}
}
