package hook

import (
	"fmt"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	compact_metric "github.com/tidbcloud/dataflow-service/app/metrics/compact_backup/metric"
	"github.com/tidbcloud/dataflow-service/app/repo/entity"
	"gorm.io/gorm"
)

type compactBackupMetricsHooker struct{}

var _ entity.DataflowEventHooker = (*compactBackupMetricsHooker)(nil)

func NewCompactBackupMetricsHooker() *compactBackupMetricsHooker {
	return &compactBackupMetricsHooker{}
}

func (h *compactBackupMetricsHooker) Type() entity.DataflowEventType {
	return entity.CompactBackupDisplayType
}

func (h *compactBackupMetricsHooker) BeforeSave(_ *gorm.DB, _ interface{}) {}

func (h *compactBackupMetricsHooker) AfterSave(_ *gorm.DB, v interface{}) {
	cb, ok := v.(*entity.CompactBackup)
	if !ok {
		return
	}
	compact_metric.UpdateCompactBackupStatusMetric(cb)
	if cb.DeletedAt != nil || cb.Status == entity.CompactBackupStatusDeleted ||
		cb.Status == entity.CompactBackupStatusSuccess || cb.Status == entity.CompactBackupStatusFailed {
		go func() {
			time.Sleep(compact_metric.WaitMetricScrapeInterval)
			compact_metric.CompactBackupStatus.DeletePartialMatch(
				prometheus.Labels{compact_metric.CompactBackupIDLabel: fmt.Sprintf("%d", cb.ID)})
		}()
	}
}
