package dedicated

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
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) - /api/v1/external/{bizType}/orgs/{orgID}/projects/{projectID}/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 (same path as old, different base URL)
	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/projects/%s/clusters/%s/alerts?%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 AlertsResponse
	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 total >= 0
	if msg := assertions.ShouldBeGreaterThanOrEqualTo(respBody.Data.Total, 0); msg != "" {
		result.AddError(fmt.Sprintf("Total should be >= 0: %s", msg))
	}

	// 5. Verify alerts is a list (can be empty)
	if respBody.Data.Alerts == nil {
		respBody.Data.Alerts = []AlertItem{}
	}

	return result
}
