package nextgen

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

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

// AlertsNewPathCase test case for alerts list API using new path (nextgen)
type AlertsNewPathCase struct {
	limit int
	page  int
}

func NewAlertsNewPathCase() *AlertsNewPathCase {
	return &AlertsNewPathCase{
		limit: 20,
		page:  1,
	}
}

func (c *AlertsNewPathCase) Name() string {
	return "AlertsListNewPath"
}

func (c *AlertsNewPathCase) Description() string {
	return "Verify alerts list API (gateway, nextgen) - /api/v1/external/{bizType}/orgs/{orgID}/clusters/{clusterID}/alerts"
}

func (c *AlertsNewPathCase) 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 time range: last 2 days
	endTime := time.Now().Unix()
	startTime := endTime - 2*24*60*60 // 2 days ago

	// Build request URL with gateway URL (no projectID for nextgen)
	params := url.Values{}
	params.Set("region", region)
	params.Set("vendor", vendor)
	params.Set("startTime", strconv.FormatInt(startTime, 10))
	params.Set("endTime", strconv.FormatInt(endTime, 10))
	params.Set("limit", strconv.Itoa(c.limit))
	params.Set("page", strconv.Itoa(c.page))

	apiURL := fmt.Sprintf("%s/api/v1/external/%s/orgs/%s/clusters/%s/alerts?%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 AlertsResponse
	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 msg := assertions.ShouldNotBeNil(respBody.Data); msg != "" {
		result.AddError(fmt.Sprintf("Data should not be nil: %s", msg))
	}

	// Verify alerts array exists (can be empty)
	if msg := assertions.ShouldNotBeNil(respBody.Data.Alerts); msg != "" {
		result.AddError(fmt.Sprintf("Alerts array should not be nil: %s", msg))
	}

	return result
}
