package service

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

	"github.com/gin-gonic/gin"
	"github.com/onsi/gomega"

	"github.com/pingcap-inc/clinic/pkg/api/common"
	"github.com/pingcap-inc/clinic/pkg/auth/session"
	_const "github.com/pingcap-inc/clinic/pkg/const"
)

func TestRebuild(t *testing.T) {
	rebuildbody := common.Rebuild{
		DataType:     int(_const.AllTask),
		ItemID:       "FileUUID_1",
		HealthReport: true,
		OrgID:        1,
		ClusterID:    "Test_01_1",
	}
	body, err := json.Marshal(rebuildbody)
	if err != nil {
		fmt.Println("", err)
		return
	}
	setHandler("POST", service.Rebuild, nil, body, "")
}

func TestGetTaskStatusParamValidateUsesConfiguredRange(t *testing.T) {
	g := gomega.NewWithT(t)
	param := &GetTaskStatusParam{
		ClusterID: "cluster-1",
		OrgID:     1,
		StartTime: 100,
		EndTime:   200,
		TaskType:  _const.MetricTask,
	}

	g.Expect(param.validate(100)).To(gomega.Succeed())
	g.Expect(param.validate(99)).To(gomega.MatchError(gomega.ContainSubstring("timestamp range is too long")))
}

func setHandler(m string, method func(c *gin.Context), params []gin.Param, body []byte, query string) (int, []byte) {
	w := httptest.NewRecorder()
	context, _ := gin.CreateTestContext(w)
	context.Set(session.CtxUserKey, &session.CtxUser{
		Username:        "test_user01",
		UserID:          1,
		Email:           "test01",
		Internal:        true,
		OrgIDInApiToken: 1,
	})
	switch m {
	case http.MethodGet:
		context.Request = httptest.NewRequest(http.MethodGet, "http://127.0.0.1:8080"+query, nil)
		context.Params = params
	case http.MethodPost:
		context.Request = httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080"+query, bytes.NewReader(body))
		context.Params = params
		context.Request.Header.Set("Content-Type", "application/json")
	case http.MethodPut:
		context.Request = httptest.NewRequest(http.MethodPut, "http://127.0.0.1:8080"+query, bytes.NewReader(body))
		context.Params = params
		context.Request.Header.Set("Content-Type", "application/json")
	case http.MethodDelete:
		context.Request = httptest.NewRequest(http.MethodDelete, "http://127.0.0.1:8080"+query, bytes.NewReader(body))
		context.Params = params
		context.Request.Header.Set("Content-Type", "application/json")
	default:
		panic(fmt.Errorf("unknow http method"))
	}
	method(context)

	body, err := io.ReadAll(w.Body)
	if err != nil {
		panic(err)
	}

	return w.Code, body
}
