package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"path"
	"strconv"
	"strings"
	"testing"
	"time"
)

func TestRun(t *testing.T) {
	targetCalls := 0
	target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		targetCalls += 1
	}))
	defer target.Close()

	p := func() int {
		s := httptest.NewServer(http.HandlerFunc(http.NotFound))
		s.Close()
		u := s.URL
		ps := strings.Split(u, ":")[2]
		n, err := strconv.Atoi(ps)
		if err != nil {
			t.Fatal(err)
		}
		return n
	}()
	tmpl := `{{ . }}`
	x := fmt.Sprintf(`http://localhost:%d`, p)
	y := target.URL
	db := path.Join(t.TempDir(), "db")

	do := func(method, body string) bool {
		req, _ := http.NewRequest(method, x, strings.NewReader(body))
		resp, err := httpc.Do(req)
		if err != nil {
			return false
		}
		resp.Body.Close()
		return true
	}

	go func() {
		if err := run(p, tmpl, y, db); err != nil {
			t.Fatal(err)
		}
	}()

	for !do(http.MethodGet, "") {
		time.Sleep(time.Millisecond * 100)
	}

	if targetCalls != 1 {
		t.Error("empty req body no called target")
	}

	if !do(http.MethodGet, "") {
		t.Error("couldnt get a second time with no body")
	} else if targetCalls != 1 {
		t.Error("no dedupe no body")
	}

	if !do(http.MethodPost, "1") {
		t.Error("couldnt get a third time with new body")
	} else if targetCalls != 2 {
		t.Error("deduped new body")
	} else if !do(http.MethodPost, "1") {
		t.Error("couldnt get a fourth time with new body again")
	} else if targetCalls != 2 {
		t.Error("no deduped new body again")
	} else if !do(http.MethodPost, "2") {
		t.Error("couldnt get a fifth time with new new body")
	} else if targetCalls != 3 {
		t.Error("deduped new new body")
	}
}
