package regionalapi

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

	"github.com/tidbcloud/observability/pkg/common/configs"

	"github.com/tidbcloud/observability/pkg/common/constants"
	"github.com/tidbcloud/observability/pkg/common/errors"
	"github.com/tidbcloud/observability/pkg/common/message"
	"github.com/tidbcloud/observability/pkg/common/structs"

	"github.com/stretchr/testify/assert"
)

func TestServiceInfo(t *testing.T) {
	configs.Init(structs.ServiceInfo{
		MonitorSpec: map[string]structs.MonitorSpec{
			"default": {
				Cpu:            "1",
				Memory:         "200Mi",
				InitialStorage: "40Gi",
				OverSell:       1,
				IsDefault:      true,
			},
			"spec1": {
				Cpu:            "2",
				Memory:         "400Mi",
				InitialStorage: "80Gi",
				OverSell:       0.5,
			},
		},
	})

	w := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/api/v1/", nil)
	testEngine.ServeHTTP(w, req)
	assert.Equal(t, http.StatusOK, w.Code)

	res := w.Result()
	defer res.Body.Close()

	data, err := io.ReadAll(res.Body)
	assert.NoError(t, err)

	result := &message.Result{
		Data: &message.GetServiceInfoResp{},
	}
	err = json.Unmarshal(data, result)
	assert.NoError(t, err)

	assert.Equal(t, errors.SUCCESS, result.Code)
	assert.Equal(t, constants.ObservabilityRegionalServer, result.Data.(*message.GetServiceInfoResp).ServiceName)
	assert.Equal(t, 2, len(result.Data.(*message.GetServiceInfoResp).AvailableSpecs))
}

func TestServiceHealth(t *testing.T) {
	t.Run("normal", func(t *testing.T) {
		body, _ := json.Marshal(message.GetServiceHealthReq{
			CommonReqInfo: structs.CommonReqInfo{
				Vendor: "aws",
				Region: "us-west-2",
			},
		})
		w := httptest.NewRecorder()

		req, _ := http.NewRequest("GET", "/api/v1/health/?vendor=aws&region=us-west-2", strings.NewReader(string(body)))
		req.Header.Set(constants.AuthorizationHeader, fmt.Sprintf("%s %s", constants.BearerPrefix, stsToken))
		testEngine.ServeHTTP(w, req)
		assert.Equal(t, http.StatusOK, w.Code)

		res := w.Result()
		defer res.Body.Close()

		data, err := io.ReadAll(res.Body)
		assert.NoError(t, err)

		result := &message.Result{
			Data: &message.GetServiceHealthResp{},
		}
		fmt.Println(string(data))
		err = json.Unmarshal(data, result)
		assert.NoError(t, err)

		assert.Equal(t, errors.SUCCESS, result.Code)
		assert.True(t, result.Data.(*message.GetServiceHealthResp).ServiceHealth)
	})
}
