package jobqueue

import (
	"fmt"
	"sync"
)

func NewCounterRunnableFromMap(data map[string]any) (*CounterRunnable, error) {
	count, ok := data["count"].(int)
	if !ok {
		return nil, fmt.Errorf("%w: Invalid count: %v", ErrInvalidData, data["count"])
	}
	return &CounterRunnable{Count: count}, nil
}

// CounterResult is a result of a counter
type CounterResult struct {
	Count int
}

// CounterRunnable is a runnable that counts
type CounterRunnable struct {
	Count int `json:"count" yaml:"count"`
	mu    sync.Mutex
}

// GetCount returns the current count
func (c *CounterRunnable) GetCount() int {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.Count
}

// Run runs the counter
func (c *CounterRunnable) Run() (RunResult[CounterResult], error) {
	c.mu.Lock()
	defer c.mu.Unlock()

	c.Count++

	return RunResult[CounterResult]{
		Status: ResultStatusSuccess,
		Data: CounterResult{
			Count: c.Count,
		},
	}, nil
}