package approveapplication_test import ( "context" "errors" "io" "log/slog" "sync" "testing" "time" "galaxy/lobby/internal/adapters/applicationinmem" "galaxy/lobby/internal/adapters/gameinmem" "galaxy/lobby/internal/adapters/gapactivationinmem" "galaxy/lobby/internal/adapters/membershipinmem" "galaxy/lobby/internal/adapters/mocks" "galaxy/lobby/internal/adapters/racenameinmem" "galaxy/lobby/internal/domain/application" "galaxy/lobby/internal/domain/common" "galaxy/lobby/internal/domain/game" "galaxy/lobby/internal/domain/membership" "galaxy/lobby/internal/ports" "galaxy/lobby/internal/service/approveapplication" "galaxy/lobby/internal/service/shared" "galaxy/notificationintent" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" ) type intentRec struct { mu sync.Mutex published []notificationintent.Intent err error } func (r *intentRec) record(_ context.Context, intent notificationintent.Intent) (string, error) { r.mu.Lock() defer r.mu.Unlock() if r.err != nil { return "", r.err } r.published = append(r.published, intent) return "1", nil } func (r *intentRec) snapshot() []notificationintent.Intent { r.mu.Lock() defer r.mu.Unlock() return append([]notificationintent.Intent(nil), r.published...) } func (r *intentRec) setErr(err error) { r.mu.Lock() defer r.mu.Unlock() r.err = err } func newIntentMock(t *testing.T, rec *intentRec) *mocks.MockIntentPublisher { t.Helper() m := mocks.NewMockIntentPublisher(gomock.NewController(t)) m.EXPECT().Publish(gomock.Any(), gomock.Any()).DoAndReturn(rec.record).AnyTimes() return m } func silentLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } func fixedClock(at time.Time) func() time.Time { return func() time.Time { return at } } type fixedIDs struct { gameID common.GameID applicationID common.ApplicationID membershipID common.MembershipID } func (f fixedIDs) NewGameID() (common.GameID, error) { return f.gameID, nil } func (f fixedIDs) NewApplicationID() (common.ApplicationID, error) { return f.applicationID, nil } func (f fixedIDs) NewInviteID() (common.InviteID, error) { return "", errors.New("not used") } func (f fixedIDs) NewMembershipID() (common.MembershipID, error) { return f.membershipID, nil } type fixture struct { now time.Time games *gameinmem.Store memberships *membershipinmem.Store applications *applicationinmem.Store directory *racenameinmem.Directory gapStore *gapactivationinmem.Store intentRec *intentRec intents *mocks.MockIntentPublisher ids fixedIDs openPublicGameID common.GameID } func newFixture(t *testing.T, maxPlayers, gapPlayers int) *fixture { t.Helper() now := time.Date(2026, 4, 25, 10, 0, 0, 0, time.UTC) dir, err := racenameinmem.NewDirectory(racenameinmem.WithClock(fixedClock(now))) require.NoError(t, err) games := gameinmem.NewStore() memberships := membershipinmem.NewStore() applications := applicationinmem.NewStore() gameRecord, err := game.New(game.NewGameInput{ GameID: "game-public", GameName: "Galactic Open", GameType: game.GameTypePublic, MinPlayers: 2, MaxPlayers: maxPlayers, StartGapHours: 2, StartGapPlayers: gapPlayers, EnrollmentEndsAt: now.Add(24 * time.Hour), TurnSchedule: "0 */6 * * *", TargetEngineVersion: "1.0.0", Now: now, }) require.NoError(t, err) gameRecord.Status = game.StatusEnrollmentOpen require.NoError(t, games.Save(context.Background(), gameRecord)) rec := &intentRec{} return &fixture{ now: now, games: games, memberships: memberships, applications: applications, directory: dir, gapStore: gapactivationinmem.NewStore(), intentRec: rec, intents: newIntentMock(t, rec), ids: fixedIDs{membershipID: "membership-fixed"}, openPublicGameID: gameRecord.GameID, } } func newService(t *testing.T, f *fixture) *approveapplication.Service { t.Helper() svc, err := approveapplication.NewService(approveapplication.Dependencies{ Games: f.games, Memberships: f.memberships, Applications: f.applications, Directory: f.directory, GapStore: f.gapStore, Intents: f.intents, IDs: f.ids, Clock: fixedClock(f.now), Logger: silentLogger(), }) require.NoError(t, err) return svc } func seedSubmittedApplication(t *testing.T, f *fixture, applicationID common.ApplicationID, userID, raceName string) application.Application { t.Helper() app, err := application.New(application.NewApplicationInput{ ApplicationID: applicationID, GameID: f.openPublicGameID, ApplicantUserID: userID, RaceName: raceName, Now: f.now, }) require.NoError(t, err) require.NoError(t, f.applications.Save(context.Background(), app)) return app } func TestApproveHappyPath(t *testing.T) { t.Parallel() f := newFixture(t, 4, 1) app := seedSubmittedApplication(t, f, "application-1", "user-1", "SolarPilot") svc := newService(t, f) got, err := svc.Handle(context.Background(), approveapplication.Input{ Actor: shared.NewAdminActor(), GameID: f.openPublicGameID, ApplicationID: app.ApplicationID, }) require.NoError(t, err) assert.Equal(t, common.MembershipID("membership-fixed"), got.MembershipID) assert.Equal(t, "SolarPilot", got.RaceName) assert.Equal(t, "solarpilot", got.CanonicalKey) assert.Equal(t, membership.StatusActive, got.Status) assert.Equal(t, f.now, got.JoinedAt) updated, err := f.applications.Get(context.Background(), app.ApplicationID) require.NoError(t, err) assert.Equal(t, application.StatusApproved, updated.Status) availability, err := f.directory.Check(context.Background(), "SolarPilot", "user-2") require.NoError(t, err) assert.True(t, availability.Taken) assert.Equal(t, "user-1", availability.HolderUserID) intents := f.intentRec.snapshot() require.Len(t, intents, 1) assert.Equal(t, notificationintent.NotificationTypeLobbyMembershipApproved, intents[0].NotificationType) assert.Equal(t, []string{"user-1"}, intents[0].RecipientUserIDs) assert.False(t, f.gapStore.WasActivated(f.openPublicGameID)) } func TestApproveActivatesGapAtMaxPlayers(t *testing.T) { t.Parallel() // max=2, gap=1; pre-seed 1 active member. Approval pushes count to 2 (== max). f := newFixture(t, 2, 1) preexisting, err := membership.New(membership.NewMembershipInput{ MembershipID: "membership-pre", GameID: f.openPublicGameID, UserID: "user-pre", RaceName: "VoidRunner", CanonicalKey: "voidrunner", Now: f.now, }) require.NoError(t, err) require.NoError(t, f.memberships.Save(context.Background(), preexisting)) app := seedSubmittedApplication(t, f, "application-1", "user-1", "SolarPilot") svc := newService(t, f) _, err = svc.Handle(context.Background(), approveapplication.Input{ Actor: shared.NewAdminActor(), GameID: f.openPublicGameID, ApplicationID: app.ApplicationID, }) require.NoError(t, err) assert.True(t, f.gapStore.WasActivated(f.openPublicGameID)) assert.Equal(t, f.now, f.gapStore.ActivatedAt(f.openPublicGameID)) } func TestApproveDoesNotActivateGapBelowMax(t *testing.T) { t.Parallel() f := newFixture(t, 4, 1) app := seedSubmittedApplication(t, f, "application-1", "user-1", "SolarPilot") svc := newService(t, f) _, err := svc.Handle(context.Background(), approveapplication.Input{ Actor: shared.NewAdminActor(), GameID: f.openPublicGameID, ApplicationID: app.ApplicationID, }) require.NoError(t, err) assert.False(t, f.gapStore.WasActivated(f.openPublicGameID)) } func TestApproveUserActorForbidden(t *testing.T) { t.Parallel() f := newFixture(t, 4, 1) app := seedSubmittedApplication(t, f, "application-1", "user-1", "SolarPilot") svc := newService(t, f) _, err := svc.Handle(context.Background(), approveapplication.Input{ Actor: shared.NewUserActor("user-1"), GameID: f.openPublicGameID, ApplicationID: app.ApplicationID, }) require.ErrorIs(t, err, shared.ErrForbidden) } func TestApproveApplicationNotFound(t *testing.T) { t.Parallel() f := newFixture(t, 4, 1) svc := newService(t, f) _, err := svc.Handle(context.Background(), approveapplication.Input{ Actor: shared.NewAdminActor(), GameID: f.openPublicGameID, ApplicationID: "application-missing", }) require.ErrorIs(t, err, application.ErrNotFound) } func TestApproveCrossGameApplicationNotFound(t *testing.T) { t.Parallel() f := newFixture(t, 4, 1) app := seedSubmittedApplication(t, f, "application-1", "user-1", "SolarPilot") svc := newService(t, f) _, err := svc.Handle(context.Background(), approveapplication.Input{ Actor: shared.NewAdminActor(), GameID: "game-other", ApplicationID: app.ApplicationID, }) require.ErrorIs(t, err, application.ErrNotFound) } func TestApproveAlreadyDecidedConflict(t *testing.T) { t.Parallel() f := newFixture(t, 4, 1) app := seedSubmittedApplication(t, f, "application-1", "user-1", "SolarPilot") require.NoError(t, f.applications.UpdateStatus(context.Background(), ports.UpdateApplicationStatusInput{ ApplicationID: app.ApplicationID, ExpectedFrom: application.StatusSubmitted, To: application.StatusRejected, At: f.now, })) svc := newService(t, f) _, err := svc.Handle(context.Background(), approveapplication.Input{ Actor: shared.NewAdminActor(), GameID: f.openPublicGameID, ApplicationID: app.ApplicationID, }) require.ErrorIs(t, err, application.ErrConflict) } func TestApproveGameNotEnrollmentOpenConflict(t *testing.T) { t.Parallel() f := newFixture(t, 4, 1) app := seedSubmittedApplication(t, f, "application-1", "user-1", "SolarPilot") rec, err := f.games.Get(context.Background(), f.openPublicGameID) require.NoError(t, err) rec.Status = game.StatusReadyToStart require.NoError(t, f.games.Save(context.Background(), rec)) svc := newService(t, f) _, err = svc.Handle(context.Background(), approveapplication.Input{ Actor: shared.NewAdminActor(), GameID: f.openPublicGameID, ApplicationID: app.ApplicationID, }) require.ErrorIs(t, err, game.ErrConflict) } func TestApproveRosterFullConflict(t *testing.T) { t.Parallel() f := newFixture(t, 2, 1) for i := range 3 { member, err := membership.New(membership.NewMembershipInput{ MembershipID: common.MembershipID("membership-seed-" + string(rune('a'+i))), GameID: f.openPublicGameID, UserID: "seed-user-" + string(rune('a'+i)), RaceName: "Seed " + string(rune('A'+i)), CanonicalKey: "seed" + string(rune('a'+i)), Now: f.now, }) require.NoError(t, err) require.NoError(t, f.memberships.Save(context.Background(), member)) } app := seedSubmittedApplication(t, f, "application-1", "user-1", "SolarPilot") svc := newService(t, f) _, err := svc.Handle(context.Background(), approveapplication.Input{ Actor: shared.NewAdminActor(), GameID: f.openPublicGameID, ApplicationID: app.ApplicationID, }) require.ErrorIs(t, err, game.ErrConflict) } func TestApproveNameTakenByAnotherUser(t *testing.T) { t.Parallel() f := newFixture(t, 4, 1) require.NoError(t, f.directory.Reserve(context.Background(), "game-other", "user-other", "SolarPilot")) app := seedSubmittedApplication(t, f, "application-1", "user-1", "SolarPilot") svc := newService(t, f) _, err := svc.Handle(context.Background(), approveapplication.Input{ Actor: shared.NewAdminActor(), GameID: f.openPublicGameID, ApplicationID: app.ApplicationID, }) require.ErrorIs(t, err, ports.ErrNameTaken) availability, err := f.directory.Check(context.Background(), "SolarPilot", "user-1") require.NoError(t, err) assert.True(t, availability.Taken) assert.Equal(t, "user-other", availability.HolderUserID) } // approveCASStub wraps applicationinmem.Store but injects ErrConflict on // the next UpdateStatus call so we can observe the rollback path. type approveCASStub struct { *applicationinmem.Store failNext bool } func (s *approveCASStub) UpdateStatus(ctx context.Context, input ports.UpdateApplicationStatusInput) error { if s.failNext { s.failNext = false return application.ErrConflict } return s.Store.UpdateStatus(ctx, input) } func TestApproveCASConflictReleasesReservation(t *testing.T) { t.Parallel() f := newFixture(t, 4, 1) app := seedSubmittedApplication(t, f, "application-1", "user-1", "SolarPilot") cas := &approveCASStub{Store: f.applications, failNext: true} svc, err := approveapplication.NewService(approveapplication.Dependencies{ Games: f.games, Memberships: f.memberships, Applications: cas, Directory: f.directory, GapStore: f.gapStore, Intents: f.intents, IDs: f.ids, Clock: fixedClock(f.now), Logger: silentLogger(), }) require.NoError(t, err) _, err = svc.Handle(context.Background(), approveapplication.Input{ Actor: shared.NewAdminActor(), GameID: f.openPublicGameID, ApplicationID: app.ApplicationID, }) require.ErrorIs(t, err, application.ErrConflict) availability, err := f.directory.Check(context.Background(), "SolarPilot", "user-2") require.NoError(t, err) assert.False(t, availability.Taken, "reservation must have been released after CAS failure") assert.Empty(t, availability.HolderUserID) } func TestApprovePublishFailureDoesNotRollback(t *testing.T) { t.Parallel() f := newFixture(t, 4, 1) app := seedSubmittedApplication(t, f, "application-1", "user-1", "SolarPilot") f.intentRec.setErr(errors.New("publish failed")) svc := newService(t, f) got, err := svc.Handle(context.Background(), approveapplication.Input{ Actor: shared.NewAdminActor(), GameID: f.openPublicGameID, ApplicationID: app.ApplicationID, }) require.NoError(t, err) assert.Equal(t, common.MembershipID("membership-fixed"), got.MembershipID) updated, err := f.applications.Get(context.Background(), app.ApplicationID) require.NoError(t, err) assert.Equal(t, application.StatusApproved, updated.Status) }