package spindle

import (
	"context"
	"testing"
	"time"

	comatproto "github.com/bluesky-social/indigo/api/atproto"

	"tangled.org/core/jetstream"
)

func TestCatchUpLaterReturnsAtOnceAndStillSavesTheDids(t *testing.T) {
	b := catchUpBackfill(t, &fakeHydrant{})

	b.CatchUpLater()
	b.CatchUpLater()
	eventually(t, 5*time.Second, "the catch-up to save its dids", func() bool {
		pending, err := b.s.db.PendingCatchUp()
		return err == nil && len(pending) > 0
	})
	b.catchUps.Wait()
}

func TestAnAccountJobFinishesItsTicketOnceTheEventIsDone(t *testing.T) {
	env := newEnsureEnv(t)
	status := "takendown"
	var log ticketLog
	e := &jetstream.Event{
		Did:     "did:plc:nobody",
		Kind:    jetstream.EventKindAccount,
		Account: &comatproto.SyncSubscribeRepos_Account{Did: "did:plc:nobody", Active: false, Status: &status},
	}

	env.s.ingestAccountJob(context.Background(), e, namedTicket{"account", &log})
	if done, dropped := log.snapshot(); len(done) != 1 || len(dropped) != 0 {
		t.Fatalf("done = %v, dropped = %v, want the ticket finished", done, dropped)
	}
}

func TestACatchUpAskedForAfterShutdownStartsNothing(t *testing.T) {
	b := catchUpBackfill(t, &fakeHydrant{})
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	b.run(ctx)

	b.CatchUpLater()
	b.catchUps.Wait()
	if pending, err := b.s.db.PendingCatchUp(); err != nil || len(pending) != 0 {
		t.Fatalf("pending = %v, %v, want a catch-up asked for after shutdown not to run", pending, err)
	}
}
