package domain_test

import (
	"cmp"
	"fmt"
	"slices"
	"testing"
	"time"

	"gitea.dwysokinski.me/twhelp/corev3/internal/domain"
	"gitea.dwysokinski.me/twhelp/corev3/internal/domain/domaintest"
	"github.com/brianvoe/gofakeit/v6"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestPlayers_Delete(t *testing.T) {
	t.Parallel()

	server := domaintest.NewServer(t)

	active := domain.BasePlayers{
		domaintest.NewBasePlayer(t),
		domaintest.NewBasePlayer(t),
		domaintest.NewBasePlayer(t),
	}

	players := domain.Players{
		domaintest.NewPlayer(t, func(cfg *domaintest.PlayerConfig) {
			cfg.ID = active[0].ID()
			cfg.ServerKey = server.Key()
		}),
		domaintest.NewPlayer(t, func(cfg *domaintest.PlayerConfig) { // should be deleted
			cfg.ServerKey = server.Key()
			cfg.TribeID = 0
		}),
		domaintest.NewPlayer(t, func(cfg *domaintest.PlayerConfig) { // should be deleted + tribe change
			cfg.ServerKey = server.Key()
		}),
		domaintest.NewPlayer(t, func(cfg *domaintest.PlayerConfig) {
			cfg.ServerKey = server.Key()
			cfg.DeletedAt = time.Now()
		}),
		domaintest.NewPlayer(t, func(cfg *domaintest.PlayerConfig) {
			cfg.ID = active[1].ID()
			cfg.ServerKey = server.Key()
		}),
		domaintest.NewPlayer(t, func(cfg *domaintest.PlayerConfig) {
			cfg.ID = active[2].ID()
			cfg.ServerKey = domaintest.RandServerKey()
		}),
	}

	expectedIDs := []int{players[1].ID(), players[2].ID()}
	expectedCreateTribeChangeParams := []struct {
		serverKey  string
		playerID   int
		oldTribeID int
		newTribeID int
	}{
		{
			serverKey:  server.Key(),
			playerID:   players[2].ID(),
			oldTribeID: players[2].TribeID(),
			newTribeID: 0,
		},
	}

	slices.Sort(expectedIDs)

	slices.SortFunc(active, func(a, b domain.BasePlayer) int {
		return cmp.Compare(a.ID(), b.ID())
	})

	slices.SortFunc(players, func(a, b domain.Player) int {
		return cmp.Or(
			cmp.Compare(a.ServerKey(), b.ServerKey()),
			cmp.Compare(a.ID(), b.ID()),
		)
	})

	ids, tribeChangesParams, err := players.Delete(server.Key(), active)
	require.NoError(t, err)
	assert.Equal(t, expectedIDs, ids)
	assert.Len(t, tribeChangesParams, len(expectedCreateTribeChangeParams))
	for i, expected := range expectedCreateTribeChangeParams {
		idx := slices.IndexFunc(tribeChangesParams, func(params domain.CreateTribeChangeParams) bool {
			return params.PlayerID() == expected.playerID && params.ServerKey() == expected.serverKey
		})
		require.GreaterOrEqualf(t, idx, 0, "expectedCreateTribeChangeParams[%d] not found", i)

		params := tribeChangesParams[idx]

		assert.Equalf(t, expected.serverKey, params.ServerKey(), "expectedCreateTribeChangeParams[%d]", i)
		assert.Equalf(t, expected.playerID, params.PlayerID(), "expectedCreateTribeChangeParams[%d]", i)
		assert.Equalf(t, expected.newTribeID, params.NewTribeID(), "expectedCreateTribeChangeParams[%d]", i)
		assert.Equalf(t, expected.oldTribeID, params.OldTribeID(), "expectedCreateTribeChangeParams[%d]", i)
	}
}

func TestNewCreatePlayerParams(t *testing.T) {
	t.Parallel()

	now := time.Now()

	server := domaintest.NewServer(t)

	players := domain.BasePlayers{
		domaintest.NewBasePlayer(t),
		domaintest.NewBasePlayer(t),
		domaintest.NewBasePlayer(t),
	}
	slices.SortFunc(players, func(a, b domain.BasePlayer) int {
		return cmp.Compare(a.ID(), b.ID())
	})

	storedPlayers := domain.Players{
		// server with random server key to verify that slice order matters
		domaintest.NewPlayer(t, func(cfg *domaintest.PlayerConfig) {
			cfg.ID = players[0].ID()
			cfg.ServerKey = domaintest.RandServerKey()
		}),
		// should update BestRank/MostPoints/MostVillages/LastActivityAt
		domaintest.NewPlayer(t, func(cfg *domaintest.PlayerConfig) {
			cfg.ID = players[0].ID()
			cfg.Points = players[0].Points() - 1
			cfg.NumVillages = players[0].NumVillages() - 1
			cfg.OD = players[0].OD()
			cfg.ServerKey = server.Key()
			cfg.BestRank = players[0].Rank() + 1
			cfg.BestRankAt = now.Add(-time.Hour)
			cfg.MostPoints = players[0].Points() - 1
			cfg.MostPointsAt = now.Add(-time.Hour)
			cfg.MostVillages = players[0].NumVillages() - 1
			cfg.MostVillagesAt = now.Add(-time.Hour)
			cfg.LastActivityAt = now.Add(-time.Hour)
		}),
		// shouldn't update BestRank/MostPoints/MostVillages/LastActivityAt
		domaintest.NewPlayer(t, func(cfg *domaintest.PlayerConfig) {
			cfg.ID = players[1].ID()
			cfg.Points = players[1].Points() + 1
			cfg.NumVillages = players[1].NumVillages() + 1
			cfg.OD = players[1].OD()
			cfg.ServerKey = server.Key()
			cfg.BestRank = players[1].Rank() - 1
			cfg.BestRankAt = now.Add(-time.Hour)
			cfg.MostPoints = players[1].Points() + 1
			cfg.MostPointsAt = now.Add(-time.Hour)
			cfg.MostVillages = players[1].NumVillages() + 1
			cfg.MostVillagesAt = now.Add(-time.Hour)
			cfg.LastActivityAt = now.Add(-time.Hour)
		}),
	}
	storedPlayersSorted := slices.Clone(storedPlayers)
	slices.SortFunc(storedPlayersSorted, func(a, b domain.Player) int {
		return cmp.Or(
			cmp.Compare(a.ServerKey(), b.ServerKey()),
			cmp.Compare(a.ID(), b.ID()),
		)
	})

	expectedParams := []struct {
		base           domain.BasePlayer
		serverKey      string
		bestRank       int
		bestRankAt     time.Time
		mostPoints     int
		mostPointsAt   time.Time
		mostVillages   int
		mostVillagesAt time.Time
		lastActivityAt time.Time
	}{
		{
			base:           players[0],
			serverKey:      server.Key(),
			bestRank:       players[0].Rank(),
			bestRankAt:     now,
			mostPoints:     players[0].Points(),
			mostPointsAt:   now,
			mostVillages:   players[0].NumVillages(),
			mostVillagesAt: now,
			lastActivityAt: now,
		},
		{
			base:           players[1],
			serverKey:      server.Key(),
			bestRank:       storedPlayers[2].BestRank(),
			bestRankAt:     storedPlayers[2].BestRankAt(),
			mostPoints:     storedPlayers[2].MostPoints(),
			mostPointsAt:   storedPlayers[2].MostPointsAt(),
			mostVillages:   storedPlayers[2].MostVillages(),
			mostVillagesAt: storedPlayers[2].MostVillagesAt(),
			lastActivityAt: storedPlayers[2].LastActivityAt(),
		},
		{
			base:           players[2],
			serverKey:      server.Key(),
			bestRank:       players[2].Rank(),
			bestRankAt:     now,
			mostPoints:     players[2].Points(),
			mostPointsAt:   now,
			mostVillages:   players[2].NumVillages(),
			mostVillagesAt: now,
			lastActivityAt: now,
		},
	}

	res, err := domain.NewCreatePlayerParams(server.Key(), players, storedPlayersSorted)
	require.NoError(t, err)
	assert.Len(t, res, len(expectedParams))
	for i, expected := range expectedParams {
		idx := slices.IndexFunc(res, func(params domain.CreatePlayerParams) bool {
			return params.Base().ID() == expected.base.ID() && params.ServerKey() == expected.serverKey
		})
		require.GreaterOrEqualf(t, idx, 0, "expectedParams[%d] not found", i)

		params := res[idx]

		assert.Equalf(t, expected.base, params.Base(), "expectedParams[%d]", i)
		assert.Equalf(t, expected.serverKey, params.ServerKey(), "expectedParams[%d]", i)
		assert.Equalf(t, expected.bestRank, params.BestRank(), "expectedParams[%d]", i)
		assert.WithinDurationf(t, expected.bestRankAt, params.BestRankAt(), time.Minute, "expectedParams[%d]", i)
		assert.Equalf(t, expected.mostPoints, params.MostPoints(), "expectedParams[%d]", i)
		assert.WithinDurationf(t, expected.mostPointsAt, params.MostPointsAt(), time.Minute, "expectedParams[%d]", i)
		assert.Equalf(t, expected.mostVillages, params.MostVillages(), "expectedParams[%d]", i)
		assert.WithinDurationf(t, expected.mostVillagesAt, params.MostVillagesAt(), time.Minute, "expectedParams[%d]", i)
		assert.WithinDurationf(t, expected.lastActivityAt, params.LastActivityAt(), time.Minute, "expectedParams[%d]", i)
	}
}

func TestNewPlayerCursor(t *testing.T) {
	t.Parallel()

	validPlayerCursor := domaintest.NewPlayerCursor(t)

	type args struct {
		id           int
		serverKey    string
		odScoreAtt   int
		odScoreDef   int
		odScoreTotal int
		points       int
		deletedAt    time.Time
	}

	type test struct {
		name        string
		args        args
		expectedErr error
	}

	tests := []test{
		{
			name: "OK",
			args: args{
				id:           validPlayerCursor.ID(),
				serverKey:    validPlayerCursor.ServerKey(),
				odScoreAtt:   validPlayerCursor.ODScoreAtt(),
				odScoreDef:   validPlayerCursor.ODScoreDef(),
				odScoreTotal: validPlayerCursor.ODScoreTotal(),
				points:       validPlayerCursor.Points(),
				deletedAt:    validPlayerCursor.DeletedAt(),
			},
			expectedErr: nil,
		},
		{
			name: "ERR: id < 1",
			args: args{
				id:           0,
				serverKey:    validPlayerCursor.ServerKey(),
				odScoreAtt:   validPlayerCursor.ODScoreAtt(),
				odScoreDef:   validPlayerCursor.ODScoreDef(),
				odScoreTotal: validPlayerCursor.ODScoreTotal(),
				points:       validPlayerCursor.Points(),
				deletedAt:    validPlayerCursor.DeletedAt(),
			},
			expectedErr: domain.ValidationError{
				Model: "PlayerCursor",
				Field: "id",
				Err: domain.MinGreaterEqualError{
					Min:     1,
					Current: 0,
				},
			},
		},
		{
			name: "ERR: odScoreAtt < 0",
			args: args{
				id:           validPlayerCursor.ID(),
				serverKey:    validPlayerCursor.ServerKey(),
				odScoreAtt:   -1,
				odScoreDef:   validPlayerCursor.ODScoreDef(),
				odScoreTotal: validPlayerCursor.ODScoreTotal(),
				points:       validPlayerCursor.Points(),
				deletedAt:    validPlayerCursor.DeletedAt(),
			},
			expectedErr: domain.ValidationError{
				Model: "PlayerCursor",
				Field: "odScoreAtt",
				Err: domain.MinGreaterEqualError{
					Min:     0,
					Current: -1,
				},
			},
		},
		{
			name: "ERR: odScoreDef < 0",
			args: args{
				id:           validPlayerCursor.ID(),
				serverKey:    validPlayerCursor.ServerKey(),
				odScoreAtt:   validPlayerCursor.ODScoreAtt(),
				odScoreDef:   -1,
				odScoreTotal: validPlayerCursor.ODScoreTotal(),
				points:       validPlayerCursor.Points(),
				deletedAt:    validPlayerCursor.DeletedAt(),
			},
			expectedErr: domain.ValidationError{
				Model: "PlayerCursor",
				Field: "odScoreDef",
				Err: domain.MinGreaterEqualError{
					Min:     0,
					Current: -1,
				},
			},
		},
		{
			name: "ERR: odScoreTotal < 0",
			args: args{
				id:           validPlayerCursor.ID(),
				serverKey:    validPlayerCursor.ServerKey(),
				odScoreAtt:   validPlayerCursor.ODScoreAtt(),
				odScoreDef:   validPlayerCursor.ODScoreDef(),
				odScoreTotal: -1,
				points:       validPlayerCursor.Points(),
				deletedAt:    validPlayerCursor.DeletedAt(),
			},
			expectedErr: domain.ValidationError{
				Model: "PlayerCursor",
				Field: "odScoreTotal",
				Err: domain.MinGreaterEqualError{
					Min:     0,
					Current: -1,
				},
			},
		},
		{
			name: "ERR: points < 0",
			args: args{
				id:           validPlayerCursor.ID(),
				serverKey:    validPlayerCursor.ServerKey(),
				odScoreAtt:   validPlayerCursor.ODScoreAtt(),
				odScoreDef:   validPlayerCursor.ODScoreDef(),
				odScoreTotal: validPlayerCursor.ODScoreTotal(),
				points:       -1,
				deletedAt:    validPlayerCursor.DeletedAt(),
			},
			expectedErr: domain.ValidationError{
				Model: "PlayerCursor",
				Field: "points",
				Err: domain.MinGreaterEqualError{
					Min:     0,
					Current: -1,
				},
			},
		},
	}

	for _, serverKeyTest := range newServerKeyValidationTests() {
		tests = append(tests, test{
			name: serverKeyTest.name,
			args: args{
				id:           validPlayerCursor.ID(),
				serverKey:    serverKeyTest.key,
				odScoreAtt:   validPlayerCursor.ODScoreAtt(),
				odScoreDef:   validPlayerCursor.ODScoreDef(),
				odScoreTotal: validPlayerCursor.ODScoreTotal(),
				points:       validPlayerCursor.Points(),
				deletedAt:    validPlayerCursor.DeletedAt(),
			},
			expectedErr: domain.ValidationError{
				Model: "PlayerCursor",
				Field: "serverKey",
				Err:   serverKeyTest.expectedErr,
			},
		})
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			tc, err := domain.NewPlayerCursor(
				tt.args.id,
				tt.args.serverKey,
				tt.args.odScoreAtt,
				tt.args.odScoreDef,
				tt.args.odScoreTotal,
				tt.args.points,
				tt.args.deletedAt,
			)
			require.ErrorIs(t, err, tt.expectedErr)
			if tt.expectedErr != nil {
				return
			}
			assert.Equal(t, tt.args.id, tc.ID())
			assert.Equal(t, tt.args.serverKey, tc.ServerKey())
			assert.Equal(t, tt.args.odScoreAtt, tc.ODScoreAtt())
			assert.Equal(t, tt.args.odScoreDef, tc.ODScoreDef())
			assert.Equal(t, tt.args.odScoreTotal, tc.ODScoreTotal())
			assert.Equal(t, tt.args.points, tc.Points())
			assert.Equal(t, tt.args.deletedAt, tc.DeletedAt())
			assert.NotEmpty(t, tc.Encode())
		})
	}
}

func TestListPlayersParams_SetIDs(t *testing.T) {
	t.Parallel()

	type args struct {
		ids []int
	}

	tests := []struct {
		name        string
		args        args
		expectedErr error
	}{
		{
			name: "OK",
			args: args{
				ids: []int{
					domaintest.RandID(),
					domaintest.RandID(),
					domaintest.RandID(),
				},
			},
		},
		{
			name: "ERR: value < 1",
			args: args{
				ids: []int{
					domaintest.RandID(),
					domaintest.RandID(),
					domaintest.RandID(),
					0,
					domaintest.RandID(),
				},
			},
			expectedErr: domain.SliceElementValidationError{
				Model: "ListPlayersParams",
				Field: "ids",
				Index: 3,
				Err: domain.MinGreaterEqualError{
					Min:     1,
					Current: 0,
				},
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			params := domain.NewListPlayersParams()

			require.ErrorIs(t, params.SetIDs(tt.args.ids), tt.expectedErr)
			if tt.expectedErr != nil {
				return
			}
			assert.Equal(t, tt.args.ids, params.IDs())
		})
	}
}

func TestListPlayersParams_SetNames(t *testing.T) {
	t.Parallel()

	type args struct {
		names []string
	}

	tests := []struct {
		name        string
		args        args
		expectedErr error
	}{
		{
			name: "OK",
			args: args{
				names: []string{
					gofakeit.LetterN(50),
					gofakeit.LetterN(50),
					gofakeit.LetterN(50),
					gofakeit.LetterN(50),
				},
			},
		},
		{
			name: "ERR: len(names) < 1",
			args: args{
				names: nil,
			},
			expectedErr: domain.ValidationError{
				Model: "ListPlayersParams",
				Field: "names",
				Err: domain.LenOutOfRangeError{
					Min:     1,
					Max:     100,
					Current: 0,
				},
			},
		},
		{
			name: "ERR: len(names) > 100",
			args: args{
				names: func() []string {
					names := make([]string, 101)
					for i := range names {
						names[i] = gofakeit.LetterN(50)
					}
					return names
				}(),
			},
			expectedErr: domain.ValidationError{
				Model: "ListPlayersParams",
				Field: "names",
				Err: domain.LenOutOfRangeError{
					Min:     1,
					Max:     100,
					Current: 101,
				},
			},
		},
		{
			name: "ERR: len(name[1]) < 1",
			args: args{
				names: []string{
					gofakeit.LetterN(50),
					"",
					gofakeit.LetterN(50),
					gofakeit.LetterN(50),
				},
			},
			expectedErr: domain.SliceElementValidationError{
				Model: "ListPlayersParams",
				Field: "names",
				Index: 1,
				Err: domain.LenOutOfRangeError{
					Min:     1,
					Max:     150,
					Current: 0,
				},
			},
		},
		{
			name: "ERR: len(name[2]) > 150",
			args: args{
				names: []string{
					gofakeit.LetterN(50),
					gofakeit.LetterN(50),
					gofakeit.LetterN(151),
					gofakeit.LetterN(50),
				},
			},
			expectedErr: domain.SliceElementValidationError{
				Model: "ListPlayersParams",
				Field: "names",
				Index: 2,
				Err: domain.LenOutOfRangeError{
					Min:     1,
					Max:     150,
					Current: 151,
				},
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			params := domain.NewListPlayersParams()

			require.ErrorIs(t, params.SetNames(tt.args.names), tt.expectedErr)
			if tt.expectedErr != nil {
				return
			}
			assert.Equal(t, tt.args.names, params.Names())
		})
	}
}

func TestListPlayersParams_SetSort(t *testing.T) {
	t.Parallel()

	type args struct {
		sort []domain.PlayerSort
	}

	tests := []struct {
		name        string
		args        args
		expectedErr error
	}{
		{
			name: "OK",
			args: args{
				sort: []domain.PlayerSort{
					domain.PlayerSortPointsASC,
					domain.PlayerSortIDASC,
					domain.PlayerSortServerKeyASC,
				},
			},
		},
		{
			name: "ERR: len(sort) < 1",
			args: args{
				sort: nil,
			},
			expectedErr: domain.ValidationError{
				Model: "ListPlayersParams",
				Field: "sort",
				Err: domain.LenOutOfRangeError{
					Min:     1,
					Max:     3,
					Current: 0,
				},
			},
		},
		{
			name: "ERR: len(sort) > 3",
			args: args{
				sort: []domain.PlayerSort{
					domain.PlayerSortDeletedAtDESC,
					domain.PlayerSortPointsASC,
					domain.PlayerSortIDASC,
					domain.PlayerSortServerKeyASC,
				},
			},
			expectedErr: domain.ValidationError{
				Model: "ListPlayersParams",
				Field: "sort",
				Err: domain.LenOutOfRangeError{
					Min:     1,
					Max:     3,
					Current: 4,
				},
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			params := domain.NewListPlayersParams()

			require.ErrorIs(t, params.SetSort(tt.args.sort), tt.expectedErr)
			if tt.expectedErr != nil {
				return
			}
			assert.Equal(t, tt.args.sort, params.Sort())
		})
	}
}

func TestListPlayersParams_PrependSortString(t *testing.T) {
	t.Parallel()

	defaultNewParams := func(t *testing.T) domain.ListPlayersParams {
		t.Helper()
		return domain.ListPlayersParams{}
	}

	type args struct {
		sort []string
	}

	tests := []struct {
		name         string
		newParams    func(t *testing.T) domain.ListPlayersParams
		args         args
		expectedSort []domain.PlayerSort
		expectedErr  error
	}{
		{
			name: "OK: [odScoreAtt:ASC, odScoreDef:ASC, odScoreTotal:ASC]",
			args: args{
				sort: []string{
					"odScoreAtt:ASC",
					"odScoreDef:ASC",
					"odScoreTotal:ASC",
				},
			},
			expectedSort: []domain.PlayerSort{
				domain.PlayerSortODScoreAttASC,
				domain.PlayerSortODScoreDefASC,
				domain.PlayerSortODScoreTotalASC,
			},
		},
		{
			name: "OK: [odScoreAtt:DESC, odScoreDef:DESC, odScoreTotal:DESC]",
			args: args{
				sort: []string{
					"odScoreAtt:DESC",
					"odScoreDef:DESC",
					"odScoreTotal:DESC",
				},
			},
			expectedSort: []domain.PlayerSort{
				domain.PlayerSortODScoreAttDESC,
				domain.PlayerSortODScoreDefDESC,
				domain.PlayerSortODScoreTotalDESC,
			},
		},
		{
			name: "OK: [points:ASC, deletedAt:ASC]",
			args: args{
				sort: []string{
					"points:ASC",
					"deletedAt:ASC",
				},
			},
			expectedSort: []domain.PlayerSort{
				domain.PlayerSortPointsASC,
				domain.PlayerSortDeletedAtASC,
			},
		},
		{
			name: "OK: [points:DESC, deletedAt:DESC]",
			args: args{
				sort: []string{
					"points:DESC",
					"deletedAt:DESC",
				},
			},
			expectedSort: []domain.PlayerSort{
				domain.PlayerSortPointsDESC,
				domain.PlayerSortDeletedAtDESC,
			},
		},
		{
			name: "ERR: len(sort) < 1",
			args: args{
				sort: nil,
			},
			expectedErr: domain.ValidationError{
				Model: "ListPlayersParams",
				Field: "sort",
				Err: domain.LenOutOfRangeError{
					Min:     1,
					Max:     3,
					Current: 0,
				},
			},
		},
		{
			name: "ERR: len(sort) > 3",
			args: args{
				sort: []string{
					"odScoreAtt:ASC",
					"odScoreDef:ASC",
					"odScoreTotal:ASC",
					"points:ASC",
				},
			},
			expectedErr: domain.ValidationError{
				Model: "ListPlayersParams",
				Field: "sort",
				Err: domain.LenOutOfRangeError{
					Min:     1,
					Max:     3,
					Current: 4,
				},
			},
		},
		{
			name: "ERR: custom params + len(sort) > 2",
			newParams: func(t *testing.T) domain.ListPlayersParams {
				t.Helper()
				params := domain.NewListPlayersParams()
				require.NoError(t, params.SetSort([]domain.PlayerSort{domain.PlayerSortIDASC}))
				return params
			},
			args: args{
				sort: []string{
					"odScoreAtt:ASC",
					"odScoreDef:ASC",
					"odScoreTotal:ASC",
				},
			},
			expectedErr: domain.ValidationError{
				Model: "ListPlayersParams",
				Field: "sort",
				Err: domain.LenOutOfRangeError{
					Min:     1,
					Max:     2,
					Current: 3,
				},
			},
		},
		{
			name:      "ERR: unsupported sort string",
			newParams: defaultNewParams,
			args: args{
				sort: []string{
					"odScoreAtt:ASC",
					"odScoreDef:ASC",
					"odScoreTotal:",
				},
			},
			expectedErr: domain.SliceElementValidationError{
				Model: "ListPlayersParams",
				Field: "sort",
				Index: 2,
				Err: domain.UnsupportedSortStringError{
					Sort: "odScoreTotal:",
				},
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			newParams := defaultNewParams
			if tt.newParams != nil {
				newParams = tt.newParams
			}
			params := newParams(t)

			require.ErrorIs(t, params.PrependSortString(tt.args.sort), tt.expectedErr)
			if tt.expectedErr != nil {
				return
			}
			assert.Equal(t, tt.expectedSort, params.Sort())
		})
	}
}

func TestListPlayersParams_SetEncodedCursor(t *testing.T) {
	t.Parallel()

	validCursor := domaintest.NewPlayerCursor(t)

	type args struct {
		cursor string
	}

	tests := []struct {
		name           string
		args           args
		expectedCursor domain.PlayerCursor
		expectedErr    error
	}{
		{
			name: "OK",
			args: args{
				cursor: validCursor.Encode(),
			},
			expectedCursor: validCursor,
		},
		{
			name: "ERR: len(cursor) < 1",
			args: args{
				cursor: "",
			},
			expectedErr: domain.ValidationError{
				Model: "ListPlayersParams",
				Field: "cursor",
				Err: domain.LenOutOfRangeError{
					Min:     1,
					Max:     1000,
					Current: 0,
				},
			},
		},
		{
			name: "ERR: len(cursor) > 1000",
			args: args{
				cursor: gofakeit.LetterN(1001),
			},
			expectedErr: domain.ValidationError{
				Model: "ListPlayersParams",
				Field: "cursor",
				Err: domain.LenOutOfRangeError{
					Min:     1,
					Max:     1000,
					Current: 1001,
				},
			},
		},
		{
			name: "ERR: malformed base64",
			args: args{
				cursor: "112345",
			},
			expectedErr: domain.ValidationError{
				Model: "ListPlayersParams",
				Field: "cursor",
				Err:   domain.ErrInvalidCursor,
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			params := domain.NewListPlayersParams()

			require.ErrorIs(t, params.SetEncodedCursor(tt.args.cursor), tt.expectedErr)
			if tt.expectedErr != nil {
				return
			}
			assert.Equal(t, tt.expectedCursor, params.Cursor())
			assert.Equal(t, tt.args.cursor, params.Cursor().Encode())
		})
	}
}

func TestListPlayersParams_SetLimit(t *testing.T) {
	t.Parallel()

	type args struct {
		limit int
	}

	tests := []struct {
		name        string
		args        args
		expectedErr error
	}{
		{
			name: "OK",
			args: args{
				limit: domain.PlayerListMaxLimit,
			},
		},
		{
			name: "ERR: limit < 1",
			args: args{
				limit: 0,
			},
			expectedErr: domain.ValidationError{
				Model: "ListPlayersParams",
				Field: "limit",
				Err: domain.MinGreaterEqualError{
					Min:     1,
					Current: 0,
				},
			},
		},
		{
			name: fmt.Sprintf("ERR: limit > %d", domain.PlayerListMaxLimit),
			args: args{
				limit: domain.PlayerListMaxLimit + 1,
			},
			expectedErr: domain.ValidationError{
				Model: "ListPlayersParams",
				Field: "limit",
				Err: domain.MaxLessEqualError{
					Max:     domain.PlayerListMaxLimit,
					Current: domain.PlayerListMaxLimit + 1,
				},
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			params := domain.NewListPlayersParams()

			require.ErrorIs(t, params.SetLimit(tt.args.limit), tt.expectedErr)
			if tt.expectedErr != nil {
				return
			}
			assert.Equal(t, tt.args.limit, params.Limit())
		})
	}
}

func TestNewListPlayersResult(t *testing.T) {
	t.Parallel()

	players := domain.Players{
		domaintest.NewPlayer(t),
		domaintest.NewPlayer(t),
		domaintest.NewPlayer(t),
	}
	next := domaintest.NewPlayer(t)

	t.Run("OK: with next", func(t *testing.T) {
		t.Parallel()

		res, err := domain.NewListPlayersResult(players, next)
		require.NoError(t, err)
		assert.Equal(t, players, res.Players())
		assert.Equal(t, players[0].ID(), res.Self().ID())
		assert.Equal(t, players[0].ServerKey(), res.Self().ServerKey())
		assert.Equal(t, next.ID(), res.Next().ID())
		assert.Equal(t, next.ServerKey(), res.Next().ServerKey())
	})

	t.Run("OK: without next", func(t *testing.T) {
		t.Parallel()

		res, err := domain.NewListPlayersResult(players, domain.Player{})
		require.NoError(t, err)
		assert.Equal(t, players, res.Players())
		assert.Equal(t, players[0].ID(), res.Self().ID())
		assert.Equal(t, players[0].ServerKey(), res.Self().ServerKey())
		assert.True(t, res.Next().IsZero())
	})

	t.Run("OK: 0 players", func(t *testing.T) {
		t.Parallel()

		res, err := domain.NewListPlayersResult(nil, domain.Player{})
		require.NoError(t, err)
		assert.Zero(t, res.Players())
		assert.True(t, res.Self().IsZero())
		assert.True(t, res.Next().IsZero())
	})
}

func TestNewListPlayersWithRelationsResult(t *testing.T) {
	t.Parallel()

	players := domain.PlayersWithRelations{
		domaintest.NewPlayerWithRelations(t),
		domaintest.NewPlayerWithRelations(t),
		domaintest.NewPlayerWithRelations(t),
	}
	next := domaintest.NewPlayerWithRelations(t)

	t.Run("OK: with next", func(t *testing.T) {
		t.Parallel()

		res, err := domain.NewListPlayersWithRelationsResult(players, next)
		require.NoError(t, err)
		assert.Equal(t, players, res.Players())
		assert.Equal(t, players[0].Player().ID(), res.Self().ID())
		assert.Equal(t, players[0].Player().ServerKey(), res.Self().ServerKey())
		assert.Equal(t, next.Player().ID(), res.Next().ID())
		assert.Equal(t, next.Player().ServerKey(), res.Next().ServerKey())
	})

	t.Run("OK: without next", func(t *testing.T) {
		t.Parallel()

		res, err := domain.NewListPlayersWithRelationsResult(players, domain.PlayerWithRelations{})
		require.NoError(t, err)
		assert.Equal(t, players, res.Players())
		assert.Equal(t, players[0].Player().ID(), res.Self().ID())
		assert.Equal(t, players[0].Player().ServerKey(), res.Self().ServerKey())
		assert.True(t, res.Next().IsZero())
	})

	t.Run("OK: 0 players", func(t *testing.T) {
		t.Parallel()

		res, err := domain.NewListPlayersWithRelationsResult(nil, domain.PlayerWithRelations{})
		require.NoError(t, err)
		assert.Zero(t, res.Players())
		assert.True(t, res.Self().IsZero())
		assert.True(t, res.Next().IsZero())
	})
}
