//go:build integration
// +build integration

package healthcheck

import (
	"bytes"
	"encoding/json"
	"io"
	"net/http"
	"testing"
	"time"

	"github.com/onsi/gomega"

	"github.com/pingcap-inc/clinic/pkg/api/healthcheck"
)

// TestIntegrationHealthCheckEndpoint 集成测试：真实调用 healthcheck endpoint
// 运行方式: go test -tags=integration -v ./pkg/task_manager/task/healthcheck/... -run TestIntegrationHealthCheckEndpoint
func TestIntegrationHealthCheckEndpoint(t *testing.T) {
	g := gomega.NewWithT(t)

	req := &healthcheck.HealthCheckJobRequest{
		ClusterId:  "1379661944646413035",
		ReportId:   "test-report-" + time.Now().Format("20060102150405"),
		DeployType: "dedicated",
		ProjectId:  "1372813089454526833",
		Provider:   "aws",
		Region:     "us-west-2",
		TenantId:   "1372813089209213994",
		TimeRangeA: healthcheck.HealthCheckTimeRange{
			Start: "2025-11-12T02:57:33Z",
			End:   "2025-11-13T02:57:33Z",
		},
		TimeRangeB: healthcheck.HealthCheckTimeRange{
			Start: "2025-11-12T02:57:33Z",
			End:   "2025-11-13T02:57:33Z",
		},
		ClusterUrls: healthcheck.HealthCheckClusterUrls{
			ClusterMetricsUrl:   "https://www.ds.us-west-2.aws.observability.tidbcloud.com/internal/metrics/035cc75b-4ecb-41c9-9fca-adba50adb2f9/api/v1/",
			DataPlaneMetricsUrl: "https://www.ds.us-west-2.aws.observability.tidbcloud.com/internal/metrics/ef59de6c-c00b-4238-a975-38cc24bf0699/api/v1/",
			SlowQueryS3Url:      "s3://o11y-prod-shared-us-west-2/deltalake/1372813089209213994/035cc75b-4ecb-41c9-9fca-adba50adb2f9/slowlogs",
		},
		TopN: 3,
		DigestDiffKeys: []string{
			"slowQueryCountDiff",
			"slowQueryDigestDiff",
			"topSqlDigestDiff",
		},
	}

	jsonData, err := json.MarshalIndent(req, "", "  ")
	g.Expect(err).To(gomega.Succeed())

	t.Logf("Request body:\n%s", string(jsonData))

	httpReq, err := http.NewRequest(http.MethodPost, healthCheckEndpoint, bytes.NewBuffer(jsonData))
	g.Expect(err).To(gomega.Succeed())

	httpReq.Header.Set("Content-Type", "application/json")

	client := &http.Client{
		Timeout: 60 * time.Second,
	}

	t.Logf("Sending request to: %s", healthCheckEndpoint)

	resp, err := client.Do(httpReq)
	g.Expect(err).To(gomega.Succeed())
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	g.Expect(err).To(gomega.Succeed())

	t.Logf("Response status: %d", resp.StatusCode)
	t.Logf("Response body: %s", string(body))

	// 根据实际接口行为调整断言
	// 目前我们只是验证请求能够发送并且返回了响应
	g.Expect(resp.StatusCode).To(gomega.BeNumerically(">=", 200))
	g.Expect(resp.StatusCode).To(gomega.BeNumerically("<", 600))
}

// TestIntegrationHealthCheckEndpointVariations 测试不同参数的变体
func TestIntegrationHealthCheckEndpointVariations(t *testing.T) {
	testCases := []struct {
		name        string
		clusterID   string
		deployType  string
		expectError bool
	}{
		{
			name:        "Valid dedicated cluster",
			clusterID:   "1379661944646413035",
			deployType:  "dedicated",
			expectError: false,
		},
		{
			name:        "Invalid cluster ID",
			clusterID:   "invalid-cluster-id",
			deployType:  "dedicated",
			expectError: true,
		},
		{
			name:        "Serverless deploy type",
			clusterID:   "1379661944646413035",
			deployType:  "serverless",
			expectError: false,
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			g := gomega.NewWithT(t)

			req := &healthcheck.HealthCheckJobRequest{
				ClusterId:  tc.clusterID,
				ReportId:   "test-report-" + time.Now().Format("20060102150405"),
				DeployType: tc.deployType,
				ProjectId:  "1372813089454526833",
				Provider:   "aws",
				Region:     "us-west-2",
				TenantId:   "1372813089209213994",
				TimeRangeA: healthcheck.HealthCheckTimeRange{
					Start: "2025-11-12T02:57:33Z",
					End:   "2025-11-13T02:57:33Z",
				},
				TimeRangeB: healthcheck.HealthCheckTimeRange{
					Start: "2025-11-12T02:57:33Z",
					End:   "2025-11-13T02:57:33Z",
				},
				ClusterUrls: healthcheck.HealthCheckClusterUrls{
					ClusterMetricsUrl:   "https://www.ds.us-west-2.aws.observability.tidbcloud.com/internal/metrics/test/api/v1/",
					DataPlaneMetricsUrl: "https://www.ds.us-west-2.aws.observability.tidbcloud.com/internal/metrics/test-dataplane/api/v1/",
					SlowQueryS3Url:      "s3://o11y-prod-shared-us-west-2/deltalake/test/slowlogs",
				},
				TopN: 3,
				DigestDiffKeys: []string{
					"slowQueryCountDiff",
				},
			}

			jsonData, err := json.Marshal(req)
			g.Expect(err).To(gomega.Succeed())

			httpReq, err := http.NewRequest(http.MethodPost, healthCheckEndpoint, bytes.NewBuffer(jsonData))
			g.Expect(err).To(gomega.Succeed())

			httpReq.Header.Set("Content-Type", "application/json")

			client := &http.Client{
				Timeout: 30 * time.Second,
			}

			resp, err := client.Do(httpReq)
			g.Expect(err).To(gomega.Succeed())
			defer resp.Body.Close()

			body, err := io.ReadAll(resp.Body)
			g.Expect(err).To(gomega.Succeed())

			t.Logf("Test case: %s", tc.name)
			t.Logf("Response status: %d", resp.StatusCode)
			t.Logf("Response body: %s", string(body))

			if tc.expectError {
				// 如果期望错误，可以接受 4xx 或 5xx 状态码
				g.Expect(resp.StatusCode).To(gomega.BeNumerically(">=", 400))
			} else {
				// 如果不期望错误，可以接受 2xx 或 3xx 状态码
				g.Expect(resp.StatusCode).To(gomega.BeNumerically(">=", 200))
				g.Expect(resp.StatusCode).To(gomega.BeNumerically("<", 400))
			}
		})
	}
}
