package spindle

import (
	"context"
	"testing"

	"github.com/bluesky-social/indigo/atproto/syntax"

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

func banDids(t *testing.T, s *Spindle, who ...syntax.DID) {
	t.Helper()
	for _, did := range who {
		if err := s.db.PutBan(db.BanEntry{SubjectDid: did}); err != nil {
			t.Fatal(err)
		}
	}
}

func TestPushByABannedUserRunsNoPipeline(t *testing.T) {
	e := newPushEnv(t)
	if e.pushNext(t) == "" {
		t.Fatal("setup: an unbanned user's push made no pipeline")
	}
	banDids(t, e.n.s, testBob)

	if uri := e.pushNext(t); uri != "" {
		t.Fatalf("a push by a banned user made pipeline %q", uri)
	}
	e.wantPipelines(t, 1, "after the pusher was banned")
}

func TestPushByABannedUserFiresNoWebhook(t *testing.T) {
	h := newHookEnv(t)
	banDids(t, h.s, testBob)

	pipeline, err := h.s.NotifyEvent(context.Background(), h.k, testRepoDid, pushEvent("refs/heads/main", "skip-ci"))
	if err != nil || pipeline != "" {
		t.Fatalf("answered %q, %v, want an empty answer without an error", pipeline, err)
	}
	h.expectNoPush(t, "a push by a banned user fired a webhook")
}

func TestPullRequestOfABannedAuthorMakesNothing(t *testing.T) {
	e := newPullEnv(t)
	banDids(t, e.n.s, testBob)

	e.ticket("open", testBob, opCreate)
	e.patch(patchOne, patchSha1, testBob)
	e.sink.expect(t, 0)
}

func TestPullRequestActionOfABannedUserMakesNothing(t *testing.T) {
	e := newPullEnv(t)
	e.ticket("open", testBob, opCreate)
	e.patch(patchOne, patchSha1, testBob)
	e.sink.expect(t, 1)

	banDids(t, e.n.s, testCarol)
	e.ticket("closed", testCarol, "update")
	e.sink.expect(t, 1)
}
