package main

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

func TestAdapterContract(t *testing.T) {
	var count atomic.Int64
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		count.Add(1)
		if r.Header.Get("Idempotency-Key") != "x" {
			t.Error("lost request key")
		}
		w.WriteHeader(http.StatusServiceUnavailable)
	}))
	defer s.Close()
	a := Adapter{s.Client()}
	status, e := a.Call(context.Background(), s.URL, "x")
	if e != nil || status != 503 || count.Load() != 1 {
		t.Fatal(status, e, count.Load())
	}
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	_, e = a.Call(ctx, s.URL, "x")
	if !errors.Is(e, context.Canceled) || count.Load() != 1 {
		t.Fatal(e, count.Load())
	}
}
