package spindle

import (
	"errors"
	"fmt"
	"net/http"
	"testing"

	"tangled.org/core/spindle/db"
)

func TestNotifyEventRefusedCommitCarriesAStatusTheKnotDrops(t *testing.T) {
	e := newPushEnv(t)
	push := e.firstPush(t)
	e.w.mu.Lock()
	e.w.cgi = nil
	e.w.mu.Unlock()

	_, err := e.notify(e.n.s, push)
	var coded interface{ HTTPStatus() int }
	if !errors.As(err, &coded) {
		t.Fatalf("err = %v, want one that carries a status", err)
	}
	status := coded.HTTPStatus()
	if status < 400 || status >= 500 || status == http.StatusRequestTimeout || status == http.StatusTooManyRequests {
		t.Fatalf("status = %d, want a 4xx the knot drops the event on", status)
	}
}

func TestNotifyEventBannedRepoIsAnsweredWithNoPipeline(t *testing.T) {
	e := newPushEnv(t)
	if err := e.n.s.db.PutBan(db.BanEntry{SubjectDid: testRepoDid}); err != nil {
		t.Fatal(err)
	}

	uri, err := e.notify(e.n.s, e.firstPush(t))
	if err != nil || uri != "" {
		t.Fatalf("answered %q, %v, want an empty answer without an error", uri, err)
	}
	e.wantPipelines(t, 0, "for a banned repo")
}

func TestNotifyEventFailedPushFiresItsWebhookOnceAcrossRetries(t *testing.T) {
	h := newHookEnv(t)
	for range 3 {
		if _, err := h.notifyErr(pushEvent("refs/heads/main")); err == nil {
			t.Fatal("setup: the push was handled although the knot has no git")
		}
	}
	h.expectPush(t)
	h.expectNoPush(t, "a retry of a failed push fired the webhook again")
}

func TestNotifyEventMalformedShasCarryAStatusTheKnotDrops(t *testing.T) {
	e := newPushEnv(t)
	push := e.firstPush(t)
	push.EventPush.NewSha = "not-a-sha"

	_, err := e.notify(e.n.s, push)
	var coded interface{ HTTPStatus() int }
	if !errors.As(err, &coded) || coded.HTTPStatus() != http.StatusUnprocessableEntity {
		t.Fatalf("err = %v, want a 422", err)
	}
}

func TestARefusalFromAnyFetchCarriesAStatusTheKnotDrops(t *testing.T) {
	// the pipeline fetch comes back wrapped, refusedAsStatus has to unwrap it
	err := refusedAsStatus(fmt.Errorf("loading pipeline: %w", errRevRefused))

	var coded interface{ HTTPStatus() int }
	if !errors.As(err, &coded) || coded.HTTPStatus() != http.StatusUnprocessableEntity {
		t.Fatalf("err = %v, want a 422", err)
	}
	if plain := errors.New("couldn't fetch the push from the knot"); refusedAsStatus(plain) != plain {
		t.Fatal("an error the knot may retry was given a status")
	}
}
