package adapter_test

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

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

func testTribeChangeRepository(t *testing.T, newRepos func(t *testing.T) repositories) {
	t.Helper()

	ctx := context.Background()

	t.Run("Create", func(t *testing.T) {
		t.Parallel()

		repos := newRepos(t)

		assertCreated := func(t *testing.T, params []domain.CreateTribeChangeParams) {
			t.Helper()

			require.NotEmpty(t, params)

			listParams := domain.NewListTribeChangesParams()
			require.NoError(t, listParams.SetServerKeys([]string{params[0].ServerKey()}))

			tribeChanges, err := repos.tribeChange.List(ctx, listParams)
			require.NoError(t, err)
			for i, p := range params {
				idx := slices.IndexFunc(tribeChanges, func(tc domain.TribeChange) bool {
					return tc.ServerKey() == p.ServerKey() &&
						tc.PlayerID() == p.PlayerID() &&
						tc.OldTribeID() == p.OldTribeID() &&
						tc.NewTribeID() == p.NewTribeID()
				})
				require.GreaterOrEqualf(t, idx, 0, "params[%d] not found", i)
				tribeChange := tribeChanges[idx]

				assert.Equalf(t, p.ServerKey(), tribeChange.ServerKey(), "params[%d]", i)
				assert.Equalf(t, p.PlayerID(), tribeChange.PlayerID(), "params[%d]", i)
				assert.Equalf(t, p.OldTribeID(), tribeChange.OldTribeID(), "params[%d]", i)
				assert.Equalf(t, p.NewTribeID(), tribeChange.NewTribeID(), "params[%d]", i)
				assert.WithinDurationf(t, time.Now(), tribeChange.CreatedAt(), time.Minute, "params[%d]", i)
			}
		}

		assertNoDuplicates := func(t *testing.T, params []domain.CreateTribeChangeParams) {
			t.Helper()

			require.NotEmpty(t, params)

			listParams := domain.NewListTribeChangesParams()
			require.NoError(t, listParams.SetServerKeys([]string{params[0].ServerKey()}))

			tribeChanges, err := repos.tribeChange.List(ctx, listParams)
			require.NoError(t, err)

			res := make(map[string][]int)

			for _, p := range params {
				key := fmt.Sprintf("%s-%d-%d-%d", p.ServerKey(), p.PlayerID(), p.OldTribeID(), p.NewTribeID())

				for i, tc := range tribeChanges {
					//nolint:lll
					if tc.ServerKey() == p.ServerKey() && tc.PlayerID() == p.PlayerID() && tc.OldTribeID() == p.OldTribeID() && tc.NewTribeID() == p.NewTribeID() {
						res[key] = append(res[key], i)
					}
				}
			}

			for key, indexes := range res {
				assert.Len(t, indexes, 1, key)
			}
		}

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

			players, err := repos.player.List(ctx, domain.NewListPlayersParams())
			require.NoError(t, err)
			require.NotEmpty(t, players)
			player := players[0]

			p1, err := domain.NewCreateTribeChangeParams(
				player.ServerKey(),
				player.ID(),
				0,
				domaintest.RandID(),
			)
			require.NoError(t, err)

			p2, err := domain.NewCreateTribeChangeParams(
				player.ServerKey(),
				player.ID(),
				p1.OldTribeID(),
				player.TribeID(),
			)
			require.NoError(t, err)

			p3, err := domain.NewCreateTribeChangeParams(
				player.ServerKey(),
				player.ID(),
				p2.NewTribeID(),
				0,
			)
			require.NoError(t, err)

			createParams := []domain.CreateTribeChangeParams{
				p1,
				p2,
				p3,
			}

			require.NoError(t, repos.tribeChange.Create(ctx, createParams...))
			assertCreated(t, createParams)

			require.NoError(t, repos.tribeChange.Create(ctx, createParams...))
			assertNoDuplicates(t, createParams)
		})

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

			require.NoError(t, repos.tribeChange.Create(ctx))
		})
	})

	t.Run("List & ListCount", func(t *testing.T) {
		t.Parallel()

		repos := newRepos(t)

		tribeChanges, listTribeChangesErr := repos.tribeChange.List(ctx, domain.NewListTribeChangesParams())
		require.NoError(t, listTribeChangesErr)
		require.NotEmpty(t, tribeChanges)
		randTribeChange := tribeChanges[0]

		tests := []struct {
			name               string
			params             func(t *testing.T) domain.ListTribeChangesParams
			assertTribeChanges func(t *testing.T, params domain.ListTribeChangesParams, tribeChanges domain.TribeChanges)
			assertError        func(t *testing.T, err error)
			assertTotal        func(t *testing.T, params domain.ListTribeChangesParams, total int)
		}{
			{
				name: "OK: default params",
				params: func(t *testing.T) domain.ListTribeChangesParams {
					t.Helper()
					return domain.NewListTribeChangesParams()
				},
				assertTribeChanges: func(t *testing.T, params domain.ListTribeChangesParams, tribeChanges domain.TribeChanges) {
					t.Helper()
					assert.NotEmpty(t, len(tribeChanges))
					assert.True(t, slices.IsSortedFunc(tribeChanges, func(a, b domain.TribeChange) int {
						if x := cmp.Compare(a.ServerKey(), b.ServerKey()); x != 0 {
							return x
						}
						if x := a.CreatedAt().Compare(b.CreatedAt()); x != 0 {
							return x
						}
						return cmp.Compare(a.ID(), b.ID())
					}))
				},
				assertError: func(t *testing.T, err error) {
					t.Helper()
					require.NoError(t, err)
				},
				assertTotal: func(t *testing.T, params domain.ListTribeChangesParams, total int) {
					t.Helper()
					assert.NotEmpty(t, total)
				},
			},
			{
				name: "OK: sort=[serverKey DESC, createdAt DESC]",
				params: func(t *testing.T) domain.ListTribeChangesParams {
					t.Helper()
					params := domain.NewListTribeChangesParams()
					require.NoError(t, params.SetSort([]domain.TribeChangeSort{
						domain.TribeChangeSortServerKeyDESC,
						domain.TribeChangeSortCreatedAtDESC,
					}))
					return params
				},
				assertTribeChanges: func(t *testing.T, params domain.ListTribeChangesParams, tribeChanges domain.TribeChanges) {
					t.Helper()
					assert.NotEmpty(t, len(tribeChanges))
					assert.True(t, slices.IsSortedFunc(tribeChanges, func(a, b domain.TribeChange) int {
						if x := cmp.Compare(a.ServerKey(), b.ServerKey()) * -1; x != 0 {
							return x
						}
						return a.CreatedAt().Compare(b.CreatedAt()) * -1
					}))
				},
				assertError: func(t *testing.T, err error) {
					t.Helper()
					require.NoError(t, err)
				},
				assertTotal: func(t *testing.T, params domain.ListTribeChangesParams, total int) {
					t.Helper()
					assert.NotEmpty(t, total)
				},
			},
			{
				name: "OK: sort=[id ASC]",
				params: func(t *testing.T) domain.ListTribeChangesParams {
					t.Helper()
					params := domain.NewListTribeChangesParams()
					require.NoError(t, params.SetSort([]domain.TribeChangeSort{
						domain.TribeChangeSortIDASC,
					}))
					return params
				},
				assertTribeChanges: func(t *testing.T, params domain.ListTribeChangesParams, tribeChanges domain.TribeChanges) {
					t.Helper()
					assert.NotEmpty(t, len(tribeChanges))
					assert.True(t, slices.IsSortedFunc(tribeChanges, func(a, b domain.TribeChange) int {
						return cmp.Compare(a.ID(), b.ID())
					}))
				},
				assertError: func(t *testing.T, err error) {
					t.Helper()
					require.NoError(t, err)
				},
				assertTotal: func(t *testing.T, params domain.ListTribeChangesParams, total int) {
					t.Helper()
					assert.NotEmpty(t, total)
				},
			},
			{
				name: "OK: sort=[id DESC]",
				params: func(t *testing.T) domain.ListTribeChangesParams {
					t.Helper()
					params := domain.NewListTribeChangesParams()
					require.NoError(t, params.SetSort([]domain.TribeChangeSort{
						domain.TribeChangeSortIDDESC,
					}))
					return params
				},
				assertTribeChanges: func(t *testing.T, params domain.ListTribeChangesParams, tribeChanges domain.TribeChanges) {
					t.Helper()
					assert.NotEmpty(t, len(tribeChanges))
					assert.True(t, slices.IsSortedFunc(tribeChanges, func(a, b domain.TribeChange) int {
						return cmp.Compare(a.ID(), b.ID()) * -1
					}))
				},
				assertError: func(t *testing.T, err error) {
					t.Helper()
					require.NoError(t, err)
				},
				assertTotal: func(t *testing.T, params domain.ListTribeChangesParams, total int) {
					t.Helper()
					assert.NotEmpty(t, total)
				},
			},
			{
				name: fmt.Sprintf("OK: serverKeys=[%s]", randTribeChange.ServerKey()),
				params: func(t *testing.T) domain.ListTribeChangesParams {
					t.Helper()
					params := domain.NewListTribeChangesParams()
					require.NoError(t, params.SetServerKeys([]string{randTribeChange.ServerKey()}))
					return params
				},
				assertTribeChanges: func(t *testing.T, params domain.ListTribeChangesParams, tribeChanges domain.TribeChanges) {
					t.Helper()

					serverKeys := params.ServerKeys()

					for _, tc := range tribeChanges {
						assert.True(t, slices.Contains(serverKeys, tc.ServerKey()))
					}
				},
				assertError: func(t *testing.T, err error) {
					t.Helper()
					require.NoError(t, err)
				},
				assertTotal: func(t *testing.T, params domain.ListTribeChangesParams, total int) {
					t.Helper()
					assert.NotEmpty(t, total)
				},
			},
			{
				name: "OK: offset=1 limit=2",
				params: func(t *testing.T) domain.ListTribeChangesParams {
					t.Helper()
					params := domain.NewListTribeChangesParams()
					require.NoError(t, params.SetOffset(1))
					require.NoError(t, params.SetLimit(2))
					return params
				},
				assertTribeChanges: func(t *testing.T, params domain.ListTribeChangesParams, tribeChanges domain.TribeChanges) {
					t.Helper()
					assert.Len(t, tribeChanges, params.Limit())
				},
				assertError: func(t *testing.T, err error) {
					t.Helper()
					require.NoError(t, err)
				},
				assertTotal: func(t *testing.T, params domain.ListTribeChangesParams, total int) {
					t.Helper()
					assert.NotEmpty(t, total)
				},
			},
		}

		for _, tt := range tests {
			tt := tt

			t.Run(tt.name, func(t *testing.T) {
				t.Parallel()

				params := tt.params(t)

				res, err := repos.tribeChange.List(ctx, params)
				tt.assertError(t, err)
				tt.assertTribeChanges(t, params, res)
			})
		}
	})
}
