package playsessions import ( "context" "testing" "time" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" "github.com/Fabled-Sword/minstrel/internal/db/dbq" "github.com/Fabled-Sword/minstrel/internal/dbtest" ) func seedTestUser(t *testing.T, pool *pgxpool.Pool) pgtype.UUID { t.Helper() u, err := dbq.New(pool).CreateUser(context.Background(), dbq.CreateUserParams{ Username: dbtest.TestUserPrefix + "tester", PasswordHash: "x", ApiTokenHash: "x", IsAdmin: false, }) if err != nil { t.Fatalf("CreateUser: %v", err) } return u.ID } // A play joins the listener's latest session when it starts within the // window of that session's last play (exactly the window still counts), and // starts a new session otherwise. One listener's plays at 0, 15, 45 and 76 // minutes walk through each case against a 30-minute window. func TestFindOrCreate_JoinsWithinTheWindowAndStartsAfterIt(t *testing.T) { pool := dbtest.Pool(t) user := seedTestUser(t, pool) q := dbq.New(pool) ctx := context.Background() t0 := time.Date(2026, 4, 25, 12, 0, 0, 0, time.UTC) play := func(after time.Duration) pgtype.UUID { t.Helper() id, err := FindOrCreate(ctx, q, user, t0.Add(after), "client-a", 30*time.Minute) if err != nil || !id.Valid { t.Fatalf("play at +%s: %v, %v", after, id, err) } return id } first := play(0) row, err := q.GetMostRecentPlaySessionForUser(ctx, user) if err != nil || row.ID != first || !row.StartedAt.Time.Equal(t0) { t.Fatalf("the first play's session = %+v, %v; want %v started at %v", row, err, first, t0) } if got := play(15 * time.Minute); got != first { t.Errorf("15 minutes later: session %v, want the same %v", got, first) } row, _ = q.GetMostRecentPlaySessionForUser(ctx, user) if !row.LastEventAt.Time.Equal(t0.Add(15*time.Minute)) || row.TrackCount != 2 { t.Errorf("after two plays: last_event_at %v, track_count %d; want %v, 2", row.LastEventAt.Time, row.TrackCount, t0.Add(15*time.Minute)) } if got := play(45 * time.Minute); got != first { t.Errorf("exactly the window after the last play: session %v, want the same %v", got, first) } if got := play(76 * time.Minute); got == first { t.Errorf("31 minutes after the last play: still session %v, want a new one", got) } }