package registry

import (
	"context"
	"errors"
)

var (
	ErrServiceUnavailable = errors.New("service unavailable")
)

const (
	StatusHealthy = "healthy"
	StatusDead    = "dead"
)

type (
	Selector struct {
		registry Registry
	}
)

func (selector *Selector) Select(ctx context.Context, name string) (node *ServiceNode, err error) {
	var (
		nodes []*ServiceNode
	)
	if nodes, err = selector.registry.Get(ctx, name); err != nil {
		return
	}
	for _, nv := range nodes {
		if nv.Status == StatusHealthy {
			node = nv
			break
		}
	}
	if node == nil {
		err = ErrServiceUnavailable
	}
	return
}

func NewSelector(registry Registry) *Selector {
	return &Selector{
		registry: registry,
	}
}
