package providers

import (
	"bytes"
	"io"
	"net/http"
	"strings"
	"testing"
)

func TestReadOAuthResponseBodyRejectsOversizedResponse(t *testing.T) {
	resp := &http.Response{
		StatusCode: http.StatusOK,
		Body: io.NopCloser(bytes.NewReader(
			bytes.Repeat([]byte("a"), maxOAuthResponseBodyBytes+1),
		)),
	}

	_, err := readOAuthResponseBody(resp)
	if err == nil || !strings.Contains(err.Error(), "exceeded") {
		t.Fatalf("expected oversized response error, got %v", err)
	}
}

func TestReadOAuthResponseBodyRejectsNonSuccessStatus(t *testing.T) {
	resp := &http.Response{
		StatusCode: http.StatusBadGateway,
		Body:       io.NopCloser(strings.NewReader("provider unavailable")),
	}

	_, err := readOAuthResponseBody(resp)
	if err == nil || !strings.Contains(err.Error(), "502") {
		t.Fatalf("expected status error, got %v", err)
	}
}

func TestReadOAuthResponseBodyHandlesEmptyErrorBody(t *testing.T) {
	resp := &http.Response{
		StatusCode: http.StatusServiceUnavailable,
		Body:       io.NopCloser(strings.NewReader("   ")),
	}

	_, err := readOAuthResponseBody(resp)
	if err == nil || !strings.Contains(err.Error(), "503") {
		t.Fatalf("expected empty-body status error, got %v", err)
	}
}

func TestReadOAuthResponseBodyTruncatesLongErrorSnippet(t *testing.T) {
	longBody := strings.Repeat("x", 400)
	resp := &http.Response{
		StatusCode: http.StatusBadRequest,
		Body:       io.NopCloser(strings.NewReader(longBody)),
	}

	_, err := readOAuthResponseBody(resp)
	if err == nil {
		t.Fatal("expected long error body to produce status error")
	}
	if !strings.Contains(err.Error(), "400") {
		t.Fatalf("expected status code in error, got %v", err)
	}
	if strings.Contains(err.Error(), strings.Repeat("x", 300)) {
		t.Fatalf("expected error snippet to be truncated, got %v", err)
	}
}
