package opworker

import (
	"context"

	"github.com/tidbcloud/account/commons/database"
	"github.com/tidbcloud/account/commons/metrics"

	"github.com/tidbcloud/account/central/utils"
	"github.com/tidbcloud/account/commons/config"
	"go.opentelemetry.io/otel"

	"github.com/tidbcloud/account/internel/dao/entity"
	"gorm.io/gorm"
)

type PocApplicationWorker struct{ GlobalWorker }

func (w PocApplicationWorker) Run(ctx context.Context) error {
	w.logger.Info("start to count successful poc applications")
	ctx, span := otel.Tracer(config.TraceComponentNameWorker).Start(ctx, "PocApplicationWorker")
	defer span.End()
	bm := utils.Begin(ctx, "PocApplicationWorker")
	defer bm.OnExit(ctx)
	err := database.Transaction(func(tx *gorm.DB) error {
		count, err := entity.NewPocApplicationQuerySet(tx).SyncedEq(true).Count()
		if count == 0 {
			w.logger.Warn("received 0 value in poc counter")
		}
		if err != nil {
			return err
		}
		metrics.PocSuccessfulCount.Set(float64(count))
		return nil
	})
	return err
}
