package runner

import (
	"context"
	"errors"
	"time"

	"github.com/easyai/easyai-ai-gateway/apps/api/internal/store"
)

const (
	taskExecutionLeaseTTL      = 5 * time.Minute
	taskExecutionRenewInterval = 30 * time.Second
)

func (s *Service) renewTaskExecutionLease(ctx context.Context, cancel context.CancelFunc, taskID string, executionToken string) {
	ticker := time.NewTicker(taskExecutionRenewInterval)
	defer ticker.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-ticker.C:
			if err := s.store.RenewTaskExecutionLease(ctx, taskID, executionToken, taskExecutionLeaseTTL); err != nil {
				if errors.Is(err, store.ErrTaskExecutionFinished) {
					return
				}
				s.logger.Warn("task execution lease lost", "taskID", taskID, "error_category", "task_execution_lease_lost")
				cancel()
				return
			}
		}
	}
}
