package spindle

import (
	"context"
	"log/slog"
	"testing"

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

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

func handleBackfilled(t *testing.T, b *backfill, evts ...tapc.Event) {
	t.Helper()
	for _, evt := range evts {
		evt.Record.Live = false
		if err := b.handle(context.Background(), evt); err != nil {
			t.Fatal(err)
		}
	}
}

func requireMarked(t *testing.T, d *db.DB, did syntax.DID, want bool, msg string) {
	t.Helper()
	if _, marked, err := d.RepoRetryRow(did); err != nil || marked != want {
		t.Fatalf("%s, marked = %v, %v", msg, marked, err)
	}
}

func TestBackfilledRecordsOnlyMarkTheirRepo(t *testing.T) {
	env := newEnsureEnv(t)
	env.serve("repo")
	b := newBackfill(env.s, slog.Default(), shortTempDir(t))

	handleBackfilled(t, b, markEvent(testRepoDid, env.spindleDid(), testOwner))
	if got := env.knot.count(); got != 0 {
		t.Fatalf("a backfilled manifest cost %d knot requests", got)
	}
	requireMarked(t, env.s.db, testRepoDid, true, "no mark for the backfilled repo")
}

func TestACatchUpMarksServedReposInsteadOfRefreshingThemOneByOne(t *testing.T) {
	env := newEnsureEnv(t)
	env.serve("repo")
	env.ensure(t)
	b := newBackfill(env.s, slog.Default(), shortTempDir(t))
	before := env.knot.count()

	if err := b.refresh(context.Background(), testRepoDid); err != nil {
		t.Fatal(err)
	}
	if got := env.knot.count(); got != before {
		t.Fatalf("the catch-up's refresh cost %d knot requests, it should leave that to the repo's job", got-before)
	}
	requireMarked(t, env.s.db, testRepoDid, true, "the served repo wasn't marked")
}
