package nmos

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
	"time"
)

type QueryClient struct {
	BaseURL    string
	HTTPClient *http.Client
}

func NewQueryClient(baseURL string) *QueryClient {
	return &QueryClient{
		BaseURL: strings.TrimRight(baseURL, "/"),
		HTTPClient: &http.Client{
			Timeout: 10 * time.Second,
		},
	}
}

func (c *QueryClient) GetSenders(ctx context.Context) ([]Sender, error) {
	var out []Sender
	if err := c.getJSON(ctx, "/x-nmos/query/v1.3/senders", &out); err != nil {
		return nil, err
	}
	return out, nil
}

func (c *QueryClient) GetReceivers(ctx context.Context) ([]Receiver, error) {
	var out []Receiver
	if err := c.getJSON(ctx, "/x-nmos/query/v1.3/receivers", &out); err != nil {
		return nil, err
	}
	return out, nil
}

func (c *QueryClient) getJSON(ctx context.Context, path string, target any) error {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+path, nil)
	if err != nil {
		return err
	}
	resp, err := c.HTTPClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
		return fmt.Errorf("NMOS query %s returned %s", path, resp.Status)
	}
	return json.NewDecoder(resp.Body).Decode(target)
}
