package test

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

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

// TestDataProxyHealthAPI 测试 DataProxy 健康检查接口
// 运行前先启动服务: go run ./cmd/api/main.go
func TestDataProxyHealthAPI(t *testing.T) {
	host := "http://127.0.0.1:8087"
	url := "/data-proxy/health"
	header := map[string]string{
		"Content-Type": "application/json",
	}

	ctx := context.Background()
	resp, err := utils.HttpRequest(ctx, *utils.NewHttpConfig(host, url, http.MethodGet, header))
	if err != nil {
		log.PlainError("DataProxy health check failed", zap.Error(err))
		t.Fatalf("Health check failed: %v", err)
	}

	log.PlainInfo("DataProxy health check success", zap.String("resp", resp))
	t.Logf("Health check response: %s", resp)
}



// TestDataProxyQueryAPI 测试 DataProxy 查询接口
// 运行前先启动服务: go run ./cmd/api/main.go
func TestDataProxyQueryAPI(t *testing.T) {
	host := "http://127.0.0.1:8087"
	url := "/data-proxy/query"
	header := map[string]string{
		"Content-Type": "application/json",
	}

	// 构建查询请求 JSON
	data := `{
		"sql": "SELECT count(*) , sum(length(digest)),\"date\" FROM \"clinic_data_proxy\".\"slow_query_logs\" WHERE \"date\" in ('20251230','20251231' ,'20260101' ,'20260102' ,'20260103') group by \"date\"",
		"clusterId": "1372813089209238420",
		"timeout": 3000000,
		"options": {
			"dataSource": "s3://o11y-prod-shared-ap-southeast-1/deltalake/1372813089209238420/11e824de-880e-4d20-8883-7a90e1b52d0e/slowlogs",
			"region": "ap-southeast-1"
		}
	}`

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

	log.PlainInfo("DataProxy query success", zap.String("resp", resp))

	// 解析查询结果
	var queryResp dto.DataProxyQueryResult
	if err := json.Unmarshal([]byte(resp), &queryResp); err != nil {
		t.Fatalf("Failed to parse query response: %v", err)
	}

	t.Logf("Query returned %d rows", len(queryResp.Rows))
	t.Logf("Query metadata: QueryID=%s, RowCount=%d, ExecutionTime=%v",
		queryResp.Metadata.QueryID,
		queryResp.Metadata.RowCount,
		queryResp.Metadata.ExecutionTime)

	// 打印前几行结果
	for i, row := range queryResp.Rows {
		if i >= 3 {
			break
		}
		t.Logf("Row %d: %v", i+1, row)
	}
}


// TestDataProxyQueryAPISimple 测试 DataProxy 查询接口（简化版）
// 运行前先启动服务: go run ./cmd/api/main.go
func TestDataProxyQueryAPISimple(t *testing.T) {
	host := "http://127.0.0.1:8087"
	url := "/data-proxy/query"
	header := map[string]string{
		"Content-Type": "application/json",
	}

	// 简单查询 - 查询特定日期的数据
	data := `{
		"sql": "SELECT count(*) as cnt, \"date\" FROM \"clinic_data_proxy\".\"slow_query_logs\" WHERE \"date\" = '20260102' GROUP BY \"date\"",
		"clusterId": "1372813089209061633",
		"timeout": 300000000000,
		"options": {
			"dataSource": "s3://o11y-prod-shared-us-east-1/deltalake/1372813089209061633/019b6fb4-1c6c-7969-9f83-8f5aae6c7974/slowlogs",
			"region": "us-east-1"
		}
	}`

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

	log.PlainInfo("TestDataProxyQueryAPISimple success", zap.Any("resp", resp))
	t.Logf("Response: %s", resp)
}

// TestDataProxyQueryAPIWithDifferentRegion 测试使用不同 region 的查询
// 运行前先启动服务: go run ./cmd/api/main.go
func TestDataProxyQueryAPIWithDifferentRegion(t *testing.T) {
	host := "http://127.0.0.1:8087"
	url := "/data-proxy/query"
	header := map[string]string{
		"Content-Type": "application/json",
	}

	// 测试指定 us-west-2 region
	data := `{
		"sql": "SELECT count(*) as cnt, \"date\" FROM \"clinic_data_proxy\".\"slow_query_logs\" WHERE \"date\" = '20260102' GROUP BY \"date\"",
		"clusterId": "1372813089209061633",
		"timeout": 300000000000,
		"options": {
			"dataSource": "s3://o11y-prod-shared-us-east-1/deltalake/1372813089209061633/019b6fb4-1c6c-7969-9f83-8f5aae6c7974/slowlogs",
			"region": "us-east-1"
		}
	}`

	ctx := context.Background()
	resp, err := utils.HttpRequest(ctx, *utils.NewHttpConfig(host, url, http.MethodPost, header, utils.BodyJson(data)))
	if err != nil {
		log.PlainError("Query with custom region failed", zap.Error(err))
		t.Logf("Query with custom region: %v (expected if data is not in us-west-2)", err)
		return
	}

	log.PlainInfo(" success", zap.Any("resp", resp))
	t.Logf("Response: %s", resp)

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

	// 验证返回的 region 是我们指定的
	if queryResp.Metadata.Region != "us-west-2" {
		t.Errorf("Expected region us-west-2, got %s", queryResp.Metadata.Region)
	}

	t.Logf("Query executed successfully in region: %s", queryResp.Metadata.Region)
	log.PlainInfo("TestDataProxyQueryAPIWithDifferentRegion success",
		zap.String("region", queryResp.Metadata.Region),
		zap.Int("rows", len(queryResp.Rows)))
}

// TestDataProxySchemaAPI 测试 DataProxy Schema 接口（GET 请求）
// 运行前先启动服务: go run ./cmd/api/main.go
func TestDataProxySchemaAPI(t *testing.T) {
	host := "http://127.0.0.1:8087"

	// 测试场景1：通过 clusterId + dataSource 和 region 获取单表 schema
	t.Run("SingleTableWithDataSource", func(t *testing.T) {
		url := "/data-proxy/schema?clusterId=1372813089209238420&tables=slow_query_logs&options.dataSource=s3://o11y-prod-shared-ap-southeast-1/deltalake/1372813089209238420/11e824de-880e-4d20-8883-7a90e1b52d0e/slowlogs&options.region=ap-southeast-1"
		header := map[string]string{
			"Content-Type": "application/json",
		}

		ctx := context.Background()
		resp, err := utils.HttpRequest(ctx, *utils.NewHttpConfig(host, url, http.MethodGet, header))
		if err != nil {
			log.PlainError("Schema query failed", zap.Error(err))
			t.Fatalf("Schema query failed: %v", err)
		}

		log.PlainInfo("Schema query success", zap.String("resp", resp))

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

		// 验证结果
		if schemaResp.Count != 1 {
			t.Errorf("Expected 1 schema, got %d", schemaResp.Count)
		}

		if len(schemaResp.Schemas) > 0 {
			schema := schemaResp.Schemas[0]
			t.Logf("Database: %s, Table: %s", schema.Database, schema.Table)
			t.Logf("Column count: %d", len(schema.Columns))
			t.Logf("Partition count: %d", len(schema.Partitions))
			t.Logf("DataSource: %s", schema.DataSource)
			t.Logf("Location: %s", schema.Location)

			// 打印前5个列
			for i, col := range schema.Columns {
				if i >= 5 {
					break
				}
				t.Logf("Column %d: %s (%s)", i+1, col.Name, col.Type)
			}
		}
	})

	// 测试场景2：通过 clusterId 自动获取 dataSource 和 region
	t.Run("SingleTableWithClusterId", func(t *testing.T) {
		url := "/data-proxy/schema?tables=slow_query_logs&clusterId=1372813089209238420"
		header := map[string]string{
			"Content-Type": "application/json",
		}

		ctx := context.Background()
		resp, err := utils.HttpRequest(ctx, *utils.NewHttpConfig(host, url, http.MethodGet, header))
		if err != nil {
			log.PlainError("Schema query with clusterId failed", zap.Error(err))
			t.Fatalf("Schema query with clusterId failed: %v", err)
		}

		log.PlainInfo("Schema query with clusterId success", zap.String("resp", resp))

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

		// 验证结果
		if schemaResp.Count != 1 {
			t.Errorf("Expected 1 schema, got %d", schemaResp.Count)
		}

		t.Logf("Schema count: %d", schemaResp.Count)
		if len(schemaResp.Schemas) > 0 {
			schema := schemaResp.Schemas[0]
			t.Logf("Auto-filled from clusterId - Database: %s, Table: %s, Region from metadata: ap-southeast-1",
				schema.Database, schema.Table)
		}
	})

	// // 测试场景3：批量获取多个表的 schema
	// t.Run("MultipleTablesWithDataSource", func(t *testing.T) {
	// 	url := "/data-proxy/schema?tables=slow_query_logs,topsql&options.dataSource=s3://o11y-prod-shared-ap-southeast-1/deltalake/1372813089209238420/11e824de-880e-4d20-8883-7a90e1b52d0e/slowlogs&options.region=ap-southeast-1"
	// 	header := map[string]string{
	// 		"Content-Type": "application/json",
	// 	}

	// 	ctx := context.Background()
	// 	resp, err := utils.HttpRequest(ctx, *utils.NewHttpConfig(host, url, http.MethodGet, header))
	// 	if err != nil {
	// 		// 注意：topsql 表可能不存在，所以这里可能会失败
	// 		log.PlainError("Batch schema query failed (expected if topsql table doesn't exist)", zap.Error(err))
	// 		t.Logf("Batch schema query: %v (expected if topsql table doesn't exist)", err)
	// 		return
	// 	}

	// 	log.PlainInfo("Batch schema query success", zap.String("resp", resp))

	// 	// 解析响应
	// 	var schemaResp dto.BatchSchemaResponse
	// 	if err := json.Unmarshal([]byte(resp), &schemaResp); err != nil {
	// 		t.Fatalf("Failed to parse batch schema response: %v", err)
	// 	}

	// 	t.Logf("Batch schema count: %d", schemaResp.Count)
	// 	for i, schema := range schemaResp.Schemas {
	// 		t.Logf("Schema %d: Database=%s, Table=%s, Columns=%d",
	// 			i+1, schema.Database, schema.Table, len(schema.Columns))
	// 	}
	// })
}
