package discovery

import "time"

type LookupRequest struct {
	RequestID string `json:"requestId,omitempty"`
}

type LookupResponse struct {
	RequestID string           `json:"requestId,omitempty"`
	Services  []ServiceSummary `json:"services,omitempty"`
	Gateways  []GatewaySummary `json:"gateways,omitempty"`
}

type ServiceSummary struct {
	ID         string   `json:"id"`
	InstanceID string   `json:"instanceId"`
	Service    string   `json:"service"`
	Ops        []string `json:"ops,omitempty"`
	Version    string   `json:"version,omitempty"`
	Healthy    bool     `json:"healthy,omitempty"`
	InvokeURI  string   `json:"invokeURI,omitempty"`
}

type GatewaySummary struct {
	ID              string                 `json:"id"`
	InstanceID      string                 `json:"instanceId"`
	Rail            string                 `json:"rail"`
	Network         string                 `json:"network,omitempty"`
	Currencies      []string               `json:"currencies,omitempty"`
	CurrencyMeta    []CurrencyAnnouncement `json:"currencyMeta,omitempty"`
	Ops             []string               `json:"ops,omitempty"`
	Limits          *Limits                `json:"limits,omitempty"`
	Version         string                 `json:"version,omitempty"`
	Healthy         bool                   `json:"healthy,omitempty"`
	RoutingPriority int                    `json:"routingPriority,omitempty"`
	InvokeURI       string                 `json:"invokeURI,omitempty"`
}

func (r *Registry) Lookup(now time.Time) LookupResponse {
	entries := r.List(now, true)
	resp := LookupResponse{
		Services: make([]ServiceSummary, 0),
		Gateways: make([]GatewaySummary, 0),
	}

	for _, entry := range entries {
		if entry.Rail != "" {
			resp.Gateways = append(resp.Gateways, GatewaySummary{
				ID:              entry.ID,
				InstanceID:      entry.InstanceID,
				Rail:            entry.Rail,
				Network:         entry.Network,
				Currencies:      cloneStrings(entry.Currencies),
				CurrencyMeta:    cloneCurrencyAnnouncements(entry.CurrencyMeta),
				Ops:             cloneStrings(entry.Operations),
				Limits:          cloneLimits(entry.Limits),
				Version:         entry.Version,
				Healthy:         entry.Healthy,
				RoutingPriority: entry.RoutingPriority,
				InvokeURI:       entry.InvokeURI,
			})
			continue
		}
		resp.Services = append(resp.Services, ServiceSummary{
			ID:         entry.ID,
			InstanceID: entry.InstanceID,
			Service:    entry.Service,
			Ops:        cloneStrings(entry.Operations),
			Version:    entry.Version,
			Healthy:    entry.Healthy,
			InvokeURI:  entry.InvokeURI,
		})
	}

	return resp
}
