package metric

import (
	"fmt"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/tidbcloud/dataflow-service/app/repo/entity"
)

const (
	NS                      = "dataflow"
	SUBSYSTEM_BACKUP_EXPORT = "backup_export"

	TenantIDLabel       = "tenant_id"
	ProjectIDLabel      = "project_id"
	ClusterIDLabel      = "cluster_id"
	BackupIDLabel       = "backup_id"
	BackupExportIDLabel = "backup_export_id"
	DAGInsIDLabel       = "dag_ins_id"
	StatusLabel         = "status"

	WaitMetricScrapeInterval = time.Minute * 2
)

var commonLabels = []string{
	TenantIDLabel,
	ProjectIDLabel,
	ClusterIDLabel,
	BackupIDLabel,
	BackupExportIDLabel,
	DAGInsIDLabel,
	StatusLabel,
}

var (
	BackupExportStatusDesc = prometheus.NewDesc(
		prometheus.BuildFQName(NS, SUBSYSTEM_BACKUP_EXPORT, "status_desc"),
		"the status of backup export jobs",
		commonLabels, nil)

	BackupExportStatus = prometheus.NewGaugeVec(
		prometheus.GaugeOpts{
			Namespace:   NS,
			Subsystem:   SUBSYSTEM_BACKUP_EXPORT,
			Name:        "status",
			Help:        "backup export status",
			ConstLabels: nil,
		}, commonLabels)
)

func UpdateBackupExportStatusMetric(export *entity.BackupExport) {
	DeleteBackupExportStatusMetric(export)

	BackupExportStatus.WithLabelValues(
		fmt.Sprintf("%d", export.TenantID),
		fmt.Sprintf("%d", export.ProjectID),
		fmt.Sprintf("%d", export.ClusterID),
		fmt.Sprintf("%d", export.BackupID),
		fmt.Sprintf("%d", export.ID),
		export.DAGInsID,
		string(export.Status),
	).Set(1)
}

func DeleteBackupExportStatusMetric(export *entity.BackupExport) {
	BackupExportStatus.DeletePartialMatch(prometheus.Labels{
		BackupExportIDLabel: fmt.Sprintf("%d", export.ID),
	})
}
