package central_thanos

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

	"github.com/pingcap/dbaas/central/config"
)

type LabelSet struct {
	MetricName          string `json:"__name__"`
	Component           string `json:"component"`
	Instance            string `json:"instance"`
	Job                 string `json:"job"`
	KubernetesNamespace string `json:"kubernetes_namespace"`
	Name                string `json:"name"`
	Replica             string `json:"replica"`
	SeedAPI             string `json:"seed_api"`
	SeedProvider        string `json:"seed_provider"`
	SeedRegion          string `json:"seed_region"`
	ShootInfra          string `json:"shoot_infra"`
	ShootName           string `json:"shoot_name"`
	Tenant              string `json:"tenant"`
	TenantID            string `json:"tenant_id"`
	TidbCluster         string `json:"tidb_cluster"`
	Type                string `json:"type"`
	SqlType             string `json:"sql_type"`
	Le                  string `json:"le"`
}

type Result struct {
	LabelSet `json:"metric"`
	Value    []interface{} `json:"value"`
}

type Response struct {
	Status string `json:"status"`
	Data   struct {
		ResultType string   `json:"resultType"`
		Result     []Result `json:"result"`
	} `json:"data"`
}

func doInstantQuery(ctx context.Context, q string) (*Response, error) {
	urlString := fmt.Sprintf("%s/api/v1/query?query=%s", config.Global().ServerConfig.ThanosAddr, url.QueryEscape(q))
	req, err := http.NewRequestWithContext(ctx, "GET", urlString, nil)
	if err != nil {
		return nil, err
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil || resp.StatusCode != http.StatusOK {
		return nil, err
	}
	defer resp.Body.Close() //nolint
	thanosNodeMemoryRespResult := Response{}
	if err := json.NewDecoder(resp.Body).Decode(&thanosNodeMemoryRespResult); err != nil {
		return nil, err
	}
	return &thanosNodeMemoryRespResult, nil
}
