package tracearr

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"
)

func TestFlexiblePlaybackNumbersAcceptTracearrStrings(t *testing.T) {
	var session Session
	if err := json.Unmarshal([]byte(`{
		"durationMs":1234,
		"progressMs":"900",
		"totalDurationMs":"1800"
	}`), &session); err != nil {
		t.Fatal(err)
	}
	if session.DurationMs != 1234 || session.ProgressMs != 900 || session.TotalDurationMs != 1800 {
		t.Fatalf("unexpected playback values: %+v", session)
	}
}

func TestHistoryFiltersExactUserAndSendsBearerToken(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if got := r.Header.Get("Authorization"); got != "Bearer trr_pub_secret" {
			t.Fatalf("authorization = %q", got)
		}
		if got := r.URL.Query().Get("serverId"); got != "server-1" {
			t.Fatalf("serverId = %q", got)
		}
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{
			"data": [
				{"mediaTitle":"Arrival","mediaType":"movie","watched":true,"user":{"id":"1","username":"Matt"}},
				{"mediaTitle":"Alien","mediaType":"movie","watched":true,"user":{"id":"2","username":"Other"}}
			],
			"meta":{"total":2,"page":1,"pageSize":100}
		}`))
	}))
	defer server.Close()

	client := New(server.URL, "trr_pub_secret", "server-1", time.Second)
	history, err := client.History(context.Background(), "matt", 20)
	if err != nil {
		t.Fatal(err)
	}
	if len(history) != 1 || history[0].MediaTitle != "Arrival" {
		t.Fatalf("history = %+v", history)
	}
}

func TestCompletionAndTelevisionDetection(t *testing.T) {
	session := Session{ProgressMs: 45, TotalDurationMs: 100, Platform: "Android TV"}
	if got := session.Completion(); got != .45 {
		t.Fatalf("completion = %v", got)
	}
	if !session.IsTelevisionSession() {
		t.Fatal("expected Android TV session")
	}
	session.Watched = true
	if got := session.Completion(); got != 1 {
		t.Fatalf("watched completion = %v", got)
	}
}

func TestUsersUsesPublicUsersEndpointAndServerScope(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/api/v1/public/users" {
			t.Fatalf("path = %q", r.URL.Path)
		}
		if got := r.URL.Query().Get("serverId"); got != "server-1" {
			t.Fatalf("serverId = %q", got)
		}
		_, _ = w.Write([]byte(`{
			"data":[{"id":"trace-user","username":"Matt","sessionCount":385}],
			"meta":{"total":1,"page":1,"pageSize":100}
		}`))
	}))
	defer server.Close()

	page, err := New(server.URL, "secret", "server-1", time.Second).
		Users(context.Background(), 1, 100)
	if err != nil {
		t.Fatal(err)
	}
	if len(page.Data) != 1 || page.Data[0].Username != "Matt" ||
		page.Data[0].SessionCount != 385 {
		t.Fatalf("users = %+v", page.Data)
	}
}
