package platform

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

func TestFetchOAuthConfig_Success(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/api/auth/config" {
			t.Errorf("path = %s, want /api/auth/config", r.URL.Path)
		}
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(map[string]any{
			"auth_mode":  "prod",
			"broker_url": "https://sso.example.net",
			"broker_app": "cdrop",
		})
	}))
	defer srv.Close()

	// trailing slash on apiBase must be tolerated
	cfg, err := FetchOAuthConfig(context.Background(), srv.URL+"/")
	if err != nil {
		t.Fatalf("FetchOAuthConfig: %v", err)
	}
	if cfg.BrokerURL != "https://sso.example.net" {
		t.Errorf("broker_url = %q", cfg.BrokerURL)
	}
	if cfg.App != "cdrop" {
		t.Errorf("app = %q, want cdrop", cfg.App)
	}
}

func TestFetchOAuthConfig_DefaultsApp(t *testing.T) {
	// broker_app omitted → defaults to "cdrop".
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(map[string]any{"broker_url": "https://sso.example.net"})
	}))
	defer srv.Close()
	cfg, err := FetchOAuthConfig(context.Background(), srv.URL)
	if err != nil {
		t.Fatalf("FetchOAuthConfig: %v", err)
	}
	if cfg.App != "cdrop" {
		t.Errorf("app = %q, want default cdrop", cfg.App)
	}
}

func TestFetchOAuthConfig_Incomplete(t *testing.T) {
	// backend missing broker_url (native login not configured) must be rejected.
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(map[string]any{"auth_mode": "prod"})
	}))
	defer srv.Close()
	if _, err := FetchOAuthConfig(context.Background(), srv.URL); err == nil {
		t.Fatal("want error for missing broker_url, got nil")
	}
}

func TestFetchOAuthConfig_BadStatus(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusInternalServerError)
	}))
	defer srv.Close()
	if _, err := FetchOAuthConfig(context.Background(), srv.URL); err == nil {
		t.Fatal("want error for 500 status, got nil")
	}
}
