package emby

import (
	"context"
	"net/http"
	"strings"
	"testing"
	"time"
)

// The authorisation header is what Emby's dashboard shows for a television, and it is the
// one string the gateway sends to a third party — so both halves are pinned: the client
// name is never the product name, and the version is the set's own build rather than a
// constant that made every device look alike.
func TestAuthHeaderCarriesClientVersion(t *testing.T) {
	client := New("http://emby:8096", "https://emby.example", "MbyATV", time.Second)

	req, err := client.newRequest(
		context.Background(), http.MethodGet, "/Items", nil,
		Credentials{DeviceID: "tv-1", DeviceName: `Living "room"`, ClientVersion: "0.2.4"}, nil,
	)
	if err != nil {
		t.Fatal(err)
	}
	got := req.Header.Get("X-Emby-Authorization")
	want := `MediaBrowser Client="MbyATV", Device="Living room", DeviceId="tv-1", Version="0.2.4"`
	if got != want {
		t.Fatalf("auth header =\n  %q\nwant\n  %q", got, want)
	}
}

func TestAuthHeaderFallsBackToGatewayVersion(t *testing.T) {
	client := New("http://emby:8096", "https://emby.example", "MbyATV", time.Second)

	req, err := client.newRequest(
		context.Background(), http.MethodGet, "/Items", nil, Credentials{}, nil,
	)
	if err != nil {
		t.Fatal(err)
	}
	got := req.Header.Get("X-Emby-Authorization")
	if strings.Contains(got, `Version=""`) || strings.Contains(got, `Version="1.0"`) {
		t.Fatalf("gateway request reported no usable version: %q", got)
	}
	if !strings.Contains(got, `Version="`+client.gatewayVersion+`"`) {
		t.Fatalf("auth header %q does not carry the gateway build %q", got, client.gatewayVersion)
	}
}
