package probe

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

func TestProviderModels(t *testing.T) {
	t.Parallel()

	t.Run("parses openai models response", func(t *testing.T) {
		t.Parallel()

		server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.URL.Path != "/v1/models" {
				t.Fatalf("path = %q, want /v1/models", r.URL.Path)
			}
			if got := r.Header.Get("Authorization"); got != "Bearer sk-test" {
				t.Fatalf("authorization = %q, want bearer auth", got)
			}
			w.Header().Set("Content-Type", "application/json")
			_, _ = w.Write([]byte(`{"data":[{"id":" kimi 2.6 "},{"id":"deepseek-ai/DeepSeek-V4-Pro"}]}`))
		}))
		defer server.Close()

		result, err := ProviderModels(context.Background(), server.URL, "sk-test")
		if err != nil {
			t.Fatalf("ProviderModels() error = %v", err)
		}
		if result.HTTPStatus != http.StatusOK {
			t.Fatalf("HTTPStatus = %d, want %d", result.HTTPStatus, http.StatusOK)
		}
		if len(result.RawModels) != 2 {
			t.Fatalf("len(RawModels) = %d, want 2", len(result.RawModels))
		}
		if result.RawModels[0] != "kimi 2.6" || result.RawModels[1] != "deepseek-ai/DeepSeek-V4-Pro" {
			t.Fatalf("RawModels = %#v, want normalized trim order", result.RawModels)
		}
	})

	t.Run("returns empty slice when upstream has no models", func(t *testing.T) {
		t.Parallel()

		server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", "application/json")
			_, _ = w.Write([]byte(`{"data":[]}`))
		}))
		defer server.Close()

		result, err := ProviderModels(context.Background(), server.URL, "sk-empty")
		if err != nil {
			t.Fatalf("ProviderModels() error = %v", err)
		}
		if result.HTTPStatus != http.StatusOK {
			t.Fatalf("HTTPStatus = %d, want %d", result.HTTPStatus, http.StatusOK)
		}
		if len(result.RawModels) != 0 {
			t.Fatalf("len(RawModels) = %d, want 0", len(result.RawModels))
		}
	})

	t.Run("classifies auth failure", func(t *testing.T) {
		t.Parallel()

		server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			http.Error(w, `{"error":"forbidden"}`, http.StatusForbidden)
		}))
		defer server.Close()

		_, err := ProviderModels(context.Background(), server.URL, "sk-nope")
		if !errors.Is(err, ErrAuthFailed) {
			t.Fatalf("ProviderModels() error = %v, want ErrAuthFailed", err)
		}
	})
}
