package dedicated

import (
	"encoding/json"
	"fmt"
	"net/url"

	"github.com/smarty/assertions"
	"github.com/tidbcloud/observability/test/webconsolee2e/framework"
)

// SharedDataKey constants for new path monitor alert rules shared data keys
const (
	KeyNewPathAlertRuleResources45For       = "newPathAlertrule_resources_45_for"
	KeyNewPathAlertRuleResources45Threshold = "newPathAlertrule_resources_45_threshold"
)

// MonitorAlertRulesNewPathCase test case for monitor alert rules API using new path
type MonitorAlertRulesNewPathCase struct{}

func NewMonitorAlertRulesNewPathCase() *MonitorAlertRulesNewPathCase {
	return &MonitorAlertRulesNewPathCase{}
}

func (c *MonitorAlertRulesNewPathCase) Name() string {
	return "MonitorAlertRulesNewPath"
}

func (c *MonitorAlertRulesNewPathCase) Description() string {
	return "Verify monitor alert rules API (gateway) - /api/v1/external/{bizType}/orgs/{orgID}/projects/{projectID}/clusters/{clusterID}/monitor-alertrules"
}

func (c *MonitorAlertRulesNewPathCase) Run(ctx *framework.TestContext) *framework.CaseResult {
	result := framework.NewCaseResult()

	// Parse regionID to get vendor and region
	vendor := ""
	region := ""
	if len(ctx.RegionID) > 0 {
		for i, ch := range ctx.RegionID {
			if ch == '-' {
				vendor = ctx.RegionID[:i]
				region = ctx.RegionID[i+1:]
				break
			}
		}
	}

	// Build request URL with gateway URL (same path as old, different base URL)
	params := url.Values{}
	params.Set("region", region)
	params.Set("vendor", vendor)

	apiURL := fmt.Sprintf("%s/api/v1/external/%s/orgs/%s/projects/%s/clusters/%s/monitor-alertrules?%s",
		ctx.O11yGatewayURL,
		ctx.BizType,
		ctx.OrgID,
		ctx.ProjectID,
		ctx.ClusterID,
		params.Encode(),
	)
	result.SetRequest("GET", apiURL, nil)

	// Send request with newpath-specific headers
	client := ctx.GetNewPathClient()
	resp, err := client.Get(apiURL)
	if err != nil {
		result.AddError(fmt.Sprintf("Request failed: %v", err))
		return result
	}

	result.SetRequestWithHeaders(result.Request.Method, result.Request.URL, resp.RequestHeaders, result.Request.Body)
	result.SetResponseWithHeaders(resp.StatusCode, resp.GetResponseHeaders(), resp.String())

	// 1. Check common response headers (CORS) - use strict mode
	checker := framework.NewCommonResponseChecker(result, ctx.Origin)
	checker.CheckCORSHeaders(resp)
	checker.CheckStatusCode(resp, 200)

	// 2. Parse response body
	var respBody MonitorAlertRulesResponse
	if err := json.Unmarshal(resp.Body, &respBody); err != nil {
		result.AddError(fmt.Sprintf("Failed to parse response JSON: %v", err))
		return result
	}

	// 3. Verify code is 0
	if msg := assertions.ShouldEqual(respBody.Code, 0); msg != "" {
		result.AddError(fmt.Sprintf("Response code should be 0: %s", msg))
	}

	// 4. Verify data is not nil
	if respBody.Data == nil {
		result.AddError("Response data should not be nil")
	}

	// 5. Parse the detailed alert rules and store in SharedData for dependent cases
	type typedResponse struct {
		Code    int               `json:"code"`
		Message string            `json:"message,omitempty"`
		Data    AlertRuleListData `json:"data"`
	}
	var typedRespBody typedResponse
	if err := json.Unmarshal(resp.Body, &typedRespBody); err == nil {
		// Find customer/resources:45 rule and store its 'for' value
		for _, group := range typedRespBody.Data.AlertRuleList {
			for _, rule := range group.Rules {
				if rule.AlertRuleID == "customer/resources:45" {
					ctx.SetSharedData(KeyNewPathAlertRuleResources45For, rule.For)
					ctx.SetSharedData(KeyNewPathAlertRuleResources45Threshold, rule.Threshold)
					break
				}
			}
		}
	}

	return result
}
