package microvm

import (
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
)

func TestUploadProxyRewritesHostAndAuth(t *testing.T) {
	var upstreamHost string
	upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if req.Host != upstreamHost {
			t.Errorf("host: got %q, want %q", req.Host, upstreamHost)
		}
		if req.URL.Path != "/sub/abc.narinfo" {
			t.Errorf("path: got %q, want /sub/abc.narinfo", req.URL.Path)
		}
		if user, pass, ok := req.BasicAuth(); !ok || user != "dawn" || pass != "woof" {
			t.Errorf("basic auth: got %q/%q/%v, want dawn/hunter2/true", user, pass, ok)
		}
		_, _ = io.WriteString(w, "ok")
	}))
	defer upstream.Close()
	upstreamHost = strings.TrimPrefix(upstream.URL, "http://")

	target, err := url.Parse("http://dawn:woof@" + upstreamHost + "/sub/")
	if err != nil {
		t.Fatal(err)
	}

	req := httptest.NewRequest(http.MethodPut, "http://127.0.0.1:10501/abc.narinfo", strings.NewReader("narinfo"))
	req.Host = "127.0.0.1:10501"
	rec := httptest.NewRecorder()
	uploadProxyHandler(target, slog.Default()).ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status: got %d, want 200; body=%q", rec.Code, rec.Body.String())
	}
}
