package services

import (
	"sync"

	"github.com/mrhid6/vantage/server/internal/grpc/pb"
)

type stepResultRegistry struct {
	mu      sync.Mutex
	pending map[string]chan *pb.StepResult
}

var StepResults = &stepResultRegistry{pending: make(map[string]chan *pb.StepResult)}

func (r *stepResultRegistry) Await(commandID string) <-chan *pb.StepResult {
	ch := make(chan *pb.StepResult, 1)
	r.mu.Lock()
	r.pending[commandID] = ch
	r.mu.Unlock()
	return ch
}

func (r *stepResultRegistry) Cancel(commandID string) {
	r.mu.Lock()
	delete(r.pending, commandID)
	r.mu.Unlock()
}

func (r *stepResultRegistry) Deliver(res *pb.StepResult) {
	if res == nil {
		return
	}
	r.mu.Lock()
	ch, ok := r.pending[res.CommandId]
	if ok {
		delete(r.pending, res.CommandId)
	}
	r.mu.Unlock()
	if ok {
		ch <- res
	}
}
