package test

import (
	"context"
	"encoding/json"
	"net/http"
	"testing"

	"github.com/pingcap-inc/clinic/clinic_data_service/pkg/log"
	"github.com/pingcap-inc/clinic/clinic_data_service/pkg/utils"
	"go.uber.org/zap"
)

// TestHealthCheckSlowQueryAnalyzeAPI 测试慢查询健康检查分析接口
// 运行前先启动服务: go run ./cmd/api/main.go
func TestHealthCheckSlowQueryAnalyzeAPI(t *testing.T) {
	host := "http://127.0.0.1:8087"
	url := "/clinic-internal/healthcheck/sql/slowquery-analyze"
	header := map[string]string{
		"Content-Type": "application/json",
	}

	// 测试场景1：标准阈值检查 - 内存和查询时间都使用默认阈值
	t.Run("StandardThresholdCheck", func(t *testing.T) {
		data := `{
			"clusterId": "10104107845298920852",
			"name": "standard-threshold-test",
			"reportId": "report-001",
			"timeRange": {
				"start": "2025-12-30T00:00:00Z",
				"end": "2026-01-03T23:59:59Z"
			},
			"clusterUrls": {
				"slowQueryS3Url": "s3://o11y-prod-shared-ap-southeast-1/deltalake/1372813089209238420/11e824de-880e-4d20-8883-7a90e1b52d0e/slowlogs"
			},
			"region": "ap-southeast-1",
			"params": {
				"memMaxThreshold": 1073741824,
				"queryTimeThreshold": 10000000000
			}
		}`

		ctx := context.Background()
		resp, err := utils.HttpRequest(ctx, *utils.NewHttpConfig(host, url, http.MethodPost, header, utils.BodyJson(data)))
		if err != nil {
			log.PlainError("Standard threshold check failed", zap.Error(err))
			t.Fatalf("Standard threshold check failed: %v", err)
		}

		log.PlainInfo("Standard threshold check success", zap.String("resp", resp))
		t.Logf("Response: %s", resp)

		// 解析响应
		var result map[string]interface{}
		if err := json.Unmarshal([]byte(resp), &result); err != nil {
			t.Fatalf("Failed to parse response: %v", err)
		}
	})

	// 测试场景2：高阈值检查 - 使用更严格的阈值（期望检测到更多异常）
	t.Run("HighThresholdCheck", func(t *testing.T) {
		data := `{
			"clusterId": "1372813089209238420",
			"name": "high-threshold-test",
			"reportId": "report-002",
			"timeRange": {
				"start": "2025-12-30T00:00:00Z",
				"end": "2026-01-03T23:59:59Z"
			},
			"clusterUrls": {
				"slowQueryS3Url": "s3://o11y-prod-shared-ap-southeast-1/deltalake/1372813089209238420/11e824de-880e-4d20-8883-7a90e1b52d0e/slowlogs"
			},
			"region": "ap-southeast-1",
			"params": {
				"memMaxThreshold": 536870912,
				"queryTimeThreshold": 5000000000
			}
		}`

		ctx := context.Background()
		resp, err := utils.HttpRequest(ctx, *utils.NewHttpConfig(host, url, http.MethodPost, header, utils.BodyJson(data)))
		if err != nil {
			log.PlainError("High threshold check failed", zap.Error(err))
			t.Fatalf("High threshold check failed: %v", err)
		}

		log.PlainInfo("High threshold check success", zap.String("resp", resp))
		t.Logf("Response: %s", resp)
	})

	// 测试场景3：短时间范围检查 - 只检查单日数据
	t.Run("ShortTimeRangeCheck", func(t *testing.T) {
		data := `{
			"clusterId": "1372813089209238420",
			"name": "short-range-test",
			"reportId": "report-003",
			"timeRange": {
				"start": "2026-01-02T00:00:00Z",
				"end": "2026-01-02T23:59:59Z"
			},
			"clusterUrls": {
				"slowQueryS3Url": "s3://o11y-prod-shared-ap-southeast-1/deltalake/1372813089209238420/11e824de-880e-4d20-8883-7a90e1b52d0e/slowlogs"
			},
			"region": "ap-southeast-1",
			"params": {
				"memMaxThreshold": 1073741824,
				"queryTimeThreshold": 10000000000
			}
		}`

		ctx := context.Background()
		resp, err := utils.HttpRequest(ctx, *utils.NewHttpConfig(host, url, http.MethodPost, header, utils.BodyJson(data)))
		if err != nil {
			log.PlainError("Short time range check failed", zap.Error(err))
			t.Fatalf("Short time range check failed: %v", err)
		}

		log.PlainInfo("Short time range check success", zap.String("resp", resp))
		t.Logf("Response: %s", resp)
	})

	// 测试场景4：不同集群检查 - 使用另一个集群 ID
	t.Run("DifferentClusterCheck", func(t *testing.T) {
		data := `{
			"clusterId": "1372813089209061633",
			"name": "different-cluster-test",
			"reportId": "report-004",
			"timeRange": {
				"start": "2026-01-02T00:00:00Z",
				"end": "2026-01-03T23:59:59Z"
			},
			"clusterUrls": {
				"slowQueryS3Url": "s3://o11y-prod-shared-us-east-1/deltalake/1372813089209061633/019b6fb4-1c6c-7969-9f83-8f5aae6c7974/slowlogs"
			},
			"region": "us-east-1",
			"params": {
				"memMaxThreshold": 1073741824,
				"queryTimeThreshold": 10000000000
			}
		}`

		ctx := context.Background()
		resp, err := utils.HttpRequest(ctx, *utils.NewHttpConfig(host, url, http.MethodPost, header, utils.BodyJson(data)))
		if err != nil {
			log.PlainError("Different cluster check failed", zap.Error(err))
			t.Logf("Different cluster check: %v (expected if data is not available in this cluster)", err)
			return
		}

		log.PlainInfo("Different cluster check success", zap.String("resp", resp))
		t.Logf("Response: %s", resp)
	})

	// 测试场景5：低阈值检查 - 使用非常宽松的阈值（期望检测到很少或没有异常）
	t.Run("LowThresholdCheck", func(t *testing.T) {
		data := `{
			"clusterId": "1372813089209238420",
			"name": "low-threshold-test",
			"reportId": "report-005",
			"timeRange": {
				"start": "2025-12-30T00:00:00Z",
				"end": "2026-01-03T23:59:59Z"
			},
			"clusterUrls": {
				"slowQueryS3Url": "s3://o11y-prod-shared-ap-southeast-1/deltalake/1372813089209238420/11e824de-880e-4d20-8883-7a90e1b52d0e/slowlogs"
			},
			"region": "ap-southeast-1",
			"params": {
				"memMaxThreshold": 10737418240,
				"queryTimeThreshold": 60
			}
		}`

		ctx := context.Background()
		resp, err := utils.HttpRequest(ctx, *utils.NewHttpConfig(host, url, http.MethodPost, header, utils.BodyJson(data)))
		if err != nil {
			log.PlainError("Low threshold check failed", zap.Error(err))
			t.Fatalf("Low threshold check failed: %v", err)
		}

		log.PlainInfo("Low threshold check success", zap.String("resp", resp))
		t.Logf("Response: %s", resp)
	})

	// 测试场景6：缺少必填参数 - 测试参数校验（应该返回错误）
	t.Run("MissingRequiredParameters", func(t *testing.T) {
		data := `{
			"clusterId": "1372813089209238420",
			"name": "missing-params-test",
			"timeRange": {
				"start": "2025-12-30T00:00:00Z",
				"end": "2026-01-03T23:59:59Z"
			}
		}`

		ctx := context.Background()
		resp, err := utils.HttpRequest(ctx, *utils.NewHttpConfig(host, url, http.MethodPost, header, utils.BodyJson(data)))
		if err != nil {
			log.PlainInfo("Missing required parameters correctly rejected", zap.Error(err))
			t.Logf("Missing required parameters correctly rejected: %v (expected behavior)", err)
			return
		}

		log.PlainInfo("Missing parameters response", zap.String("resp", resp))
		t.Logf("Response: %s", resp)
	})

	// 测试场景7：Metrics 健康检查分析接口
	t.Run("MetricsHealthCheckAnalyze", func(t *testing.T) {
		metricsUrl := "/clinic-internal/healthcheck/metrics/analyze"
		data := `{
			"name": "metrics_healthcheck",
			"clusterId": "10989049060142230334",
			"physicalClusterId": "",
			"reportId": "saas01",
			"clusterUrls": {
				"clusterMetricsUrl": "https://www.ds.us-east-1.aws.observability.tidbcloud.com/internal/metrics/019b7039-041a-7b94-8cba-b308565aebdf/api/v1/",
				"dataPlaneMetricsUrl": "https://www.ds.us-east-1.aws.observability.tidbcloud.com/internal/metrics/0c252928-4d3c-4029-b157-8b866adb3d67/api/v1/",
				"slowQueryS3Url": "s3://o11y-prod-shared-us-east-1/deltalake/1372813089209061633/019b7039-041a-7b94-8cba-b308565aebdf/slowlogs"
			},
			"deployType": "dedicated",
			"projectId": "1372813089454544954",
			"provider": "aws",
			"region": "us-east-1",
			"tenantId": "1372813089209061633",
			"timeRange": {
				"start": "2026-02-08T16:00:00Z",
				"end": "2026-02-09T16:00:00Z"
			}
		}`

		ctx := context.Background()
		resp, err := utils.HttpRequest(ctx, *utils.NewHttpConfig(host, metricsUrl, http.MethodPost, header, utils.BodyJson(data)))
		if err != nil {
			log.PlainError("Metrics healthcheck analyze failed", zap.Error(err))
			t.Fatalf("Metrics healthcheck analyze failed: %v", err)
		}

		log.PlainInfo("Metrics healthcheck analyze success", zap.String("resp", resp))
		t.Logf("Response: %s", resp)

		var result map[string]interface{}
		if err := json.Unmarshal([]byte(resp), &result); err != nil {
			t.Fatalf("Failed to parse response: %v", err)
		}
	})

	// 测试场景8：长时间范围检查 - 检查一周数据
	t.Run("LongTimeRangeCheck", func(t *testing.T) {
		data := `{
			"clusterId": "1372813089209238420",
			"name": "long-range-test",
			"reportId": "report-007",
			"timeRange": {
				"start": "2025-12-28T00:00:00Z",
				"end": "2026-01-03T23:59:59Z"
			},
			"clusterUrls": {
				"slowQueryS3Url": "s3://o11y-prod-shared-ap-southeast-1/deltalake/1372813089209238420/11e824de-880e-4d20-8883-7a90e1b52d0e/slowlogs"
			},
			"region": "ap-southeast-1",
			"params": {
				"memMaxThreshold": 1073741824,
				"queryTimeThreshold": 10000000000
			}
		}`

		ctx := context.Background()
		resp, err := utils.HttpRequest(ctx, *utils.NewHttpConfig(host, url, http.MethodPost, header, utils.BodyJson(data)))
		if err != nil {
			log.PlainError("Long time range check failed", zap.Error(err))
			t.Logf("Long time range check: %v (expected if data is not available for all dates)", err)
			return
		}

		log.PlainInfo("Long time range check success", zap.String("resp", resp))
		t.Logf("Response: %s", resp)
	})
}
