package branch_svc

import (
	"strconv"
	"time"

	"github.com/pingcap/errcode"
	"github.com/tidbcloud/pkgv2/bizerr"
	"github.com/tidbcloud/serverless-service/internal/metric"
)

type (
	metricType   string
	metricMethod string
)

const (
	MetricTypeV1beta1                metricType   = "openapi_v1beta1"
	MetricTypeV1beta                 metricType   = "openapi_v1beta"
	MetricTypeRPC                    metricType   = "rpc"
	MetricTypeConsole                metricType   = "console"
	MetricMethodListBranches         metricMethod = "listBranches"
	MetricMethodCreateBranch         metricMethod = "createBranch"
	MetricMethodDeleteBranch         metricMethod = "deleteBranch"
	MetricMethodGetBranch            metricMethod = "getBranch"
	MetricMethodChangeBranchPassword metricMethod = "changeBranchPassword"
	MetricMethodCreateDBUser         metricMethod = "createDBUser"
	MetricMethodDeleteDBUser         metricMethod = "deleteDBUser"
	MetricMethodListDatabases        metricMethod = "listDatabases"
	MetricMethodResetBranch          metricMethod = "resetBranch"
	MetricMethodUpdateBranch         metricMethod = "updateBranch"
	MetricMethodUpdateSqlUser        metricMethod = "updateSqlUser"
)

func CollectBranchMetrics(metricType metricType, method metricMethod, start time.Time, err error) {
	code := metric.RequestSuccess
	if err != nil {
		code = metric.RequestUnknown
		if bizErr, ok := err.(bizerr.BizError); ok {
			code = strconv.FormatInt(int64(bizErr.ErrCode()), 10)
		}
		if errCode, ok := err.(errcode.ErrorCode); ok {
			code = string(errCode.Code().CodeStr())
		}
	}
	metric.BranchRequestedCounter.WithLabelValues(string(metricType), string(method), code).Inc()
	metric.BranchRequestedHistogram.WithLabelValues(string(metricType), string(method), code).
		Observe(time.Since(start).Seconds())
}
