package ai

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

	"git.warky.dev/wdevs/amcs/internal/ai/compat"
	"git.warky.dev/wdevs/amcs/internal/config"
)

func TestNewRegistryOpenRouterHeaders(t *testing.T) {
	var (
		gotReferer string
		gotTitle   string
		gotCustom  string
	)
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		gotReferer = r.Header.Get("HTTP-Referer")
		gotTitle = r.Header.Get("X-Title")
		gotCustom = r.Header.Get("X-Custom")
		_ = json.NewEncoder(w).Encode(map[string]any{
			"choices": []map[string]any{{"message": map[string]any{"role": "assistant", "content": "ok"}}},
		})
	}))
	defer srv.Close()

	providers := map[string]config.ProviderConfig{
		"router": {
			Type:    "openrouter",
			BaseURL: srv.URL,
			APIKey:  "secret",
			RequestHeaders: map[string]string{
				"X-Custom": "value",
			},
			AppName: "amcs",
			SiteURL: "https://example.com",
		},
	}

	reg, err := NewRegistry(providers, srv.Client(), nil)
	if err != nil {
		t.Fatalf("NewRegistry() error = %v", err)
	}

	client, err := reg.Client("router")
	if err != nil {
		t.Fatalf("Client(router) error = %v", err)
	}

	if _, err := client.SummarizeWith(context.Background(), compat.SummarizeOptions{Model: "gpt-4.1-mini"}, "system", "user"); err != nil {
		t.Fatalf("SummarizeWith() error = %v", err)
	}
	if gotReferer != "https://example.com" {
		t.Fatalf("HTTP-Referer = %q, want https://example.com", gotReferer)
	}
	if gotTitle != "amcs" {
		t.Fatalf("X-Title = %q, want amcs", gotTitle)
	}
	if gotCustom != "value" {
		t.Fatalf("X-Custom = %q, want value", gotCustom)
	}
}

func TestNewRegistryRejectsUnsupportedProviderType(t *testing.T) {
	providers := map[string]config.ProviderConfig{
		"bad": {
			Type:    "unknown",
			BaseURL: "http://localhost:4000/v1",
			APIKey:  "secret",
		},
	}

	_, err := NewRegistry(providers, &http.Client{}, nil)
	if err == nil {
		t.Fatal("NewRegistry() error = nil, want unsupported provider type error")
	}
}
