package webrtc

import (
	"context"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	"github.com/pion/webrtc/v4"
)

func TestWHEP_POSTReturns201WithSDP(t *testing.T) {
	// Set up a Source and register it.
	src, _ := NewSource("streamA", 0)
	defer src.Close()
	src.Start()

	reg := NewRegistry()
	_ = reg.Register("streamA", src)

	factory, _ := NewPeerFactory(DefaultConfig())

	handler := NewWHEPHandler(reg, factory, DefaultConfig())

	// Build an offer using a throwaway PC.
	me := &webrtc.MediaEngine{}
	_ = me.RegisterDefaultCodecs()
	api := webrtc.NewAPI(webrtc.WithMediaEngine(me))
	pc, _ := api.NewPeerConnection(webrtc.Configuration{})
	defer pc.Close()
	_, _ = pc.AddTransceiverFromKind(webrtc.RTPCodecTypeVideo,
		webrtc.RTPTransceiverInit{Direction: webrtc.RTPTransceiverDirectionRecvonly})
	_, _ = pc.AddTransceiverFromKind(webrtc.RTPCodecTypeAudio,
		webrtc.RTPTransceiverInit{Direction: webrtc.RTPTransceiverDirectionRecvonly})
	offer, _ := pc.CreateOffer(nil)

	req := httptest.NewRequest(http.MethodPost, "/whep/streamA",
		strings.NewReader(offer.SDP))
	req.Header.Set("Content-Type", "application/sdp")
	// Give the handler generous ICE gathering time in tests.
	ctx, cancel := context.WithTimeout(req.Context(), 10*time.Second)
	defer cancel()
	req = req.WithContext(ctx)

	rr := httptest.NewRecorder()
	handler.ServeHTTP(rr, req)

	if rr.Code != http.StatusCreated {
		body, _ := io.ReadAll(rr.Result().Body)
		t.Fatalf("status = %d, want 201. body=%s", rr.Code, string(body))
	}
	if ct := rr.Header().Get("Content-Type"); ct != "application/sdp" {
		t.Errorf("Content-Type = %q, want application/sdp", ct)
	}
	if loc := rr.Header().Get("Location"); !strings.HasPrefix(loc, "/whep/streamA/") {
		t.Errorf("Location = %q, want /whep/streamA/<id>", loc)
	}
	if !strings.Contains(rr.Body.String(), "v=0") {
		t.Errorf("body does not look like SDP: %s", rr.Body.String())
	}
}
