package api

import (
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	"github.com/ponzischeme89/memby/server/internal/emby"
	"github.com/ponzischeme89/memby/server/internal/store"
)

func TestStoppedPlaybackReportRemainsRetryableWhenEmbyIsDown(t *testing.T) {
	upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		http.Error(w, "temporarily unavailable", http.StatusServiceUnavailable)
	}))
	defer upstream.Close()

	s := &Server{
		emby: emby.New(upstream.URL, upstream.URL, "Memby test", time.Second),
		log:  slog.New(slog.NewTextHandler(io.Discard, nil)),
	}
	req := httptest.NewRequest(
		http.MethodPost,
		"/v1/playback/stopped",
		strings.NewReader(`{"itemId":"episode-1","positionMs":42000}`),
	)
	req.SetPathValue("phase", "stopped")
	rec := httptest.NewRecorder()

	s.handlePlaybackReport(rec, req, store.Session{EmbyUserID: "user-1", EmbyToken: "token"})

	if rec.Code != http.StatusBadGateway {
		t.Fatalf("status = %d, want 502 so the TV retries the durable stop", rec.Code)
	}
}
