package clients

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

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

func TestLocalUnsupportedKindDoesNotMarkUpstreamSubmissionStarted(t *testing.T) {
	started, responseReceived := false, false
	_, err := (VolcesClient{}).Run(context.Background(), Request{
		Kind: "speech.generations",
		Candidate: store.RuntimeModelCandidate{
			Provider: "volces", Credentials: map[string]any{"apiKey": "test"},
		},
		OnUpstreamSubmissionStarted: func() error { started = true; return nil },
		OnUpstreamResponseReceived:  func() error { responseReceived = true; return nil },
	})
	if err == nil || ErrorCode(err) != "unsupported_kind" {
		t.Fatalf("expected local unsupported_kind, got %v", err)
	}
	if started || responseReceived {
		t.Fatalf("local validation must remain not_submitted: started=%v response=%v", started, responseReceived)
	}
}

func TestNetworkDisconnectMarksSubmittingWithoutResponseReceived(t *testing.T) {
	upstream := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
	baseURL := upstream.URL
	upstream.Close()
	started, responseReceived := false, false
	_, err := (VolcesClient{HTTPClient: upstream.Client()}).Run(context.Background(), Request{
		Kind: "images.generations",
		Body: map[string]any{"prompt": "test"},
		Candidate: store.RuntimeModelCandidate{
			Provider: "volces", BaseURL: baseURL, ModelName: "seedream-test",
			Credentials: map[string]any{"apiKey": "test"},
		},
		OnUpstreamSubmissionStarted: func() error { started = true; return nil },
		OnUpstreamResponseReceived:  func() error { responseReceived = true; return nil },
	})
	if err == nil || ErrorCode(err) != "network" {
		t.Fatalf("expected network error, got %v", err)
	}
	if !started || responseReceived {
		t.Fatalf("network disconnect must remain submitting: started=%v response=%v", started, responseReceived)
	}
}
