// Package opworker is the background worker of the central service.
// The central service records intent to make changes.
// The worker finds those in the database, performs them, and updates the database.
package worker

import (
	"context"
	"fmt"
	"time"

	"github.com/tidbcloud/dataflow-service/internal/metrics"
	"github.com/tidbcloud/pkgv2/worker"
)

func withMetrics(tenantID uint64, workerName string, f worker.Handler) worker.Handler {
	return func(ctx context.Context) error {
		tBegin := time.Now()
		status := metrics.LoopOK
		err := f(ctx)
		if err != nil {
			status = metrics.LoopError
		}
		duration := float64(time.Since(tBegin)) / float64(time.Millisecond)
		metrics.WorkerDuration.WithLabelValues(fmt.Sprintf("%d", tenantID), workerName, status).Observe(duration)
		return err
	}
}
