package nextgen

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

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

// MonitorAlertRulesNewPathCase test case for monitor alert rules API using new path (nextgen)
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, nextgen) - /api/v1/external/{bizType}/orgs/{orgID}/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 (no projectID for nextgen)
	params := url.Values{}
	params.Set("region", region)
	params.Set("vendor", vendor)

	apiURL := fmt.Sprintf("%s/api/v1/external/%s/orgs/%s/clusters/%s/monitor-alertrules?%s",
		ctx.O11yGatewayURL,
		ctx.BizType,
		ctx.OrgID,
		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())

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

	// 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
	}

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

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

	// Parse the detailed alert rules and store in SharedData for dependent cases
	// Re-parse to get the typed structure
	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/resource_usage:5 rule and store its 'for' and 'threshold' values
		for _, group := range typedRespBody.Data.AlertRuleList {
			for _, rule := range group.Rules {
				if rule.AlertRuleID == "customer/resource_usage:5" {
					ctx.SetSharedData("newpath_alertrule_resource_usage_5_for", rule.For)
					ctx.SetSharedData("newpath_alertrule_resource_usage_5_threshold", rule.Threshold)
					break
				}
			}
		}
	}

	return result
}
