package httpapi

import (
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/easyai/easyai-ai-gateway/apps/api/internal/clients"
)

func TestResponsesStreamWriterForwardsStandardEventsAndNeverWritesDoneMarker(t *testing.T) {
	recorder := httptest.NewRecorder()
	writer := newCompatibleStreamWriter("responses", "demo", true)
	writer.writeDelta(recorder, clients.StreamDeltaEvent{Event: map[string]any{
		"type": "response.created", "response": map[string]any{"id": "resp_123", "status": "in_progress"},
	}})
	writer.writeDelta(recorder, clients.StreamDeltaEvent{Event: map[string]any{
		"type": "response.function_call_arguments.delta", "item_id": "fc_1", "delta": "{\"x\":",
	}})
	writer.writeDelta(recorder, clients.StreamDeltaEvent{Event: map[string]any{
		"type": "response.completed", "sequence_number": 2, "response": map[string]any{"id": "resp_123", "status": "completed", "output": []any{}},
	}})
	writer.writeDone(recorder, map[string]any{"id": "resp_123", "object": "response", "status": "completed", "output": []any{}})
	body := recorder.Body.String()
	for _, expected := range []string{"event: response.created", "event: response.function_call_arguments.delta", "event: response.completed"} {
		if !strings.Contains(body, expected) {
			t.Fatalf("missing %q in stream: %s", expected, body)
		}
	}
	if strings.Contains(body, "[DONE]") || strings.Contains(body, "chat.completion") {
		t.Fatalf("Responses stream leaked Chat framing: %s", body)
	}
	if strings.Count(body, "event: response.completed") != 1 {
		t.Fatalf("Responses stream duplicated response.completed: %s", body)
	}
}

func TestResponsesStreamWriterUsesIncompleteTerminalWithoutAppendingCompleted(t *testing.T) {
	recorder := httptest.NewRecorder()
	writer := newCompatibleStreamWriter("responses", "demo", false)
	writer.writeDelta(recorder, clients.StreamDeltaEvent{Event: map[string]any{
		"type": "response.incomplete", "sequence_number": 3, "response": map[string]any{"id": "resp_123", "status": "incomplete"},
	}})
	writer.writeDone(recorder, map[string]any{"id": "resp_123", "status": "incomplete"})
	body := recorder.Body.String()
	if strings.Count(body, "event: response.incomplete") != 1 || strings.Contains(body, "event: response.completed") {
		t.Fatalf("incomplete terminal event was duplicated or rewritten: %s", body)
	}
}
