package hook

import (
	"fmt"
	"time"

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

type restoreMetricsHooker struct{}

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

func NewRestoreMetricsHooker() *restoreMetricsHooker {
	return &restoreMetricsHooker{}
}

func (b *restoreMetricsHooker) BeforeSave(tx *gorm.DB, v interface{}) {
}

func (b *restoreMetricsHooker) AfterSave(tx *gorm.DB, v interface{}) {
	r, ok := v.(*entity.Restore)
	if !ok {
		return
	}
	restore_metric.UpdateRestoreStatusMetric(r)
	// delete the metrics of the restores that are in final status
	// note that prometheus will scrape the metrics every 1 minute, so we delete the metrics after 2 minute
	// to make sure prometheus has scraped the metrics
	// we may introduce worker pool to do this job in the future(check goroutine metrics in after launch this feature)
	if r.Status == entity.RestoreStatusFAILED || r.Status != entity.RestoreStatusSUCCESS {
		go func() {
			time.Sleep(restore_metric.WaitMetricScrapeInterval)
			restore_metric.RestoreStatus.DeletePartialMatch(
				prometheus.Labels{restore_metric.RestoreIDLabel: fmt.Sprintf("%d", r.ID)})
		}()
	}
}

func (b *restoreMetricsHooker) Type() entity.DataflowEventType {
	return entity.RestoreDisplayType
}
