package adapter_test

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

	"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 testVillageRepository(t *testing.T, newRepos func(t *testing.T) repositories) {
	t.Helper()

	ctx := context.Background()

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

		repos := newRepos(t)

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

			require.NotEmpty(t, params)

			ids := make([]int, 0, len(params))
			for _, p := range params {
				ids = append(ids, p.Base().ID())
			}

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

			villages, err := repos.village.List(ctx, listParams)
			require.NoError(t, err)
			assert.Len(t, villages, len(params))
			for i, p := range params {
				idx := slices.IndexFunc(villages, func(village domain.Village) bool {
					return village.ID() == p.Base().ID() && village.ServerKey() == p.ServerKey()
				})
				require.GreaterOrEqualf(t, idx, 0, "params[%d]", i)
				village := villages[idx]

				assert.Equalf(t, p.Base(), village.Base(), "params[%d]", i)
				assert.Equalf(t, p.ServerKey(), village.ServerKey(), "params[%d]", i)
			}
		}

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

			servers, err := repos.server.List(ctx, domain.NewListServersParams())
			require.NoError(t, err)
			require.NotEmpty(t, servers)
			server := servers[0]

			villagesToCreate := domain.BaseVillages{
				domaintest.NewBaseVillage(t),
				domaintest.NewBaseVillage(t),
			}

			createParams, err := domain.NewCreateVillageParams(server.Key(), villagesToCreate)
			require.NoError(t, err)

			require.NoError(t, repos.village.CreateOrUpdate(ctx, createParams...))
			assertCreatedUpdated(t, createParams)

			villagesToUpdate := domain.BaseVillages{
				domaintest.NewBaseVillage(t, func(cfg *domaintest.BaseVillageConfig) {
					cfg.ID = villagesToCreate[0].ID()
				}),
			}

			updateParams, err := domain.NewCreateVillageParams(server.Key(), villagesToUpdate)
			require.NoError(t, err)

			require.NoError(t, repos.village.CreateOrUpdate(ctx, updateParams...))
			assertCreatedUpdated(t, updateParams)
		})

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

			require.NoError(t, repos.village.CreateOrUpdate(ctx))
		})
	})

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

		repos := newRepos(t)

		villages, listVillagesErr := repos.village.List(ctx, domain.NewListVillagesParams())
		require.NoError(t, listVillagesErr)
		require.NotEmpty(t, villages)
		randVillage := villages[0]

		tests := []struct {
			name           string
			params         func(t *testing.T) domain.ListVillagesParams
			assertVillages func(t *testing.T, params domain.ListVillagesParams, villages domain.Villages)
			assertError    func(t *testing.T, err error)
			assertTotal    func(t *testing.T, params domain.ListVillagesParams, total int)
		}{
			{
				name: "OK: default params",
				params: func(t *testing.T) domain.ListVillagesParams {
					t.Helper()
					return domain.NewListVillagesParams()
				},
				assertVillages: func(t *testing.T, params domain.ListVillagesParams, villages domain.Villages) {
					t.Helper()
					assert.NotEmpty(t, len(villages))
					assert.True(t, slices.IsSortedFunc(villages, func(a, b domain.Village) int {
						if x := cmp.Compare(a.ServerKey(), b.ServerKey()); 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.ListVillagesParams, total int) {
					t.Helper()
					assert.NotEmpty(t, total)
				},
			},
			{
				name: "OK: sort=[serverKey DESC, id DESC]",
				params: func(t *testing.T) domain.ListVillagesParams {
					t.Helper()
					params := domain.NewListVillagesParams()
					require.NoError(t, params.SetSort([]domain.VillageSort{domain.VillageSortServerKeyDESC, domain.VillageSortIDDESC}))
					return params
				},
				assertVillages: func(t *testing.T, params domain.ListVillagesParams, villages domain.Villages) {
					t.Helper()
					assert.NotEmpty(t, len(villages))
					assert.True(t, slices.IsSortedFunc(villages, func(a, b domain.Village) int {
						if x := cmp.Compare(a.ServerKey(), b.ServerKey()) * -1; x != 0 {
							return x
						}
						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.ListVillagesParams, total int) {
					t.Helper()
					assert.NotEmpty(t, total)
				},
			},
			{
				name: fmt.Sprintf("OK: ids=[%d] serverKeys=[%s]", randVillage.ID(), randVillage.ServerKey()),
				params: func(t *testing.T) domain.ListVillagesParams {
					t.Helper()
					params := domain.NewListVillagesParams()
					require.NoError(t, params.SetIDs([]int{randVillage.ID()}))
					require.NoError(t, params.SetServerKeys([]string{randVillage.ServerKey()}))
					return params
				},
				assertVillages: func(t *testing.T, params domain.ListVillagesParams, villages domain.Villages) {
					t.Helper()

					ids := params.IDs()
					serverKeys := params.ServerKeys()

					for _, v := range villages {
						assert.True(t, slices.Contains(ids, v.ID()))
						assert.True(t, slices.Contains(serverKeys, v.ServerKey()))
					}
				},
				assertError: func(t *testing.T, err error) {
					t.Helper()
					require.NoError(t, err)
				},
				assertTotal: func(t *testing.T, params domain.ListVillagesParams, total int) {
					t.Helper()
					assert.NotEmpty(t, total)
				},
			},
			{
				name: fmt.Sprintf("OK: idGT=%d", randVillage.ID()),
				params: func(t *testing.T) domain.ListVillagesParams {
					t.Helper()
					params := domain.NewListVillagesParams()
					require.NoError(t, params.SetIDGT(domain.NullInt{
						Value: randVillage.ID(),
						Valid: true,
					}))
					return params
				},
				assertVillages: func(t *testing.T, params domain.ListVillagesParams, villages domain.Villages) {
					t.Helper()
					assert.NotEmpty(t, villages)
					for _, v := range villages {
						assert.Greater(t, v.ID(), params.IDGT().Value, v.ID())
					}
				},
				assertError: func(t *testing.T, err error) {
					t.Helper()
					require.NoError(t, err)
				},
				assertTotal: func(t *testing.T, params domain.ListVillagesParams, total int) {
					t.Helper()
					assert.NotEmpty(t, total)
				},
			},
			{
				name: "OK: offset=1 limit=2",
				params: func(t *testing.T) domain.ListVillagesParams {
					t.Helper()
					params := domain.NewListVillagesParams()
					require.NoError(t, params.SetOffset(1))
					require.NoError(t, params.SetLimit(2))
					return params
				},
				assertVillages: func(t *testing.T, params domain.ListVillagesParams, villages domain.Villages) {
					t.Helper()
					assert.Len(t, villages, params.Limit())
				},
				assertError: func(t *testing.T, err error) {
					t.Helper()
					require.NoError(t, err)
				},
				assertTotal: func(t *testing.T, params domain.ListVillagesParams, 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.village.List(ctx, params)
				tt.assertError(t, err)
				tt.assertVillages(t, params, res)
			})
		}
	})

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

		repos := newRepos(t)

		listServersParams := domain.NewListServersParams()
		require.NoError(t, listServersParams.SetSpecial(domain.NullBool{Value: false, Valid: true}))
		servers, listServersErr := repos.server.List(ctx, listServersParams)
		require.NoError(t, listServersErr)
		require.NotEmpty(t, servers)

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

			serverKeys := make([]string, 0, len(servers))
			for _, s := range servers {
				serverKeys = append(serverKeys, s.Key())
			}

			listVillagesParams := domain.NewListVillagesParams()
			require.NoError(t, listVillagesParams.SetServerKeys(serverKeys))

			villagesBeforeDelete, err := repos.village.List(ctx, listVillagesParams)
			require.NoError(t, err)

			var serverKey string
			var ids []int

			for _, v := range villagesBeforeDelete {
				if serverKey == "" {
					serverKey = v.ServerKey()
				}

				if v.ServerKey() == serverKey {
					ids = append(ids, v.ID())
				}
			}

			idsToDelete := ids[:int(math.Ceil(float64(len(ids))/2))]

			require.NoError(t, repos.village.Delete(ctx, serverKey, idsToDelete...))

			villagesAfterDelete, err := repos.village.List(ctx, listVillagesParams)
			require.NoError(t, err)
			assert.Len(t, villagesAfterDelete, len(villagesBeforeDelete)-len(idsToDelete))
			for _, v := range villagesAfterDelete {
				if v.ServerKey() == serverKey && slices.Contains(ids, v.ID()) {
					assert.False(t, slices.Contains(idsToDelete, v.ID()))
				}
			}
		})

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

			require.NoError(t, repos.village.Delete(ctx, servers[0].Key()))
		})
	})
}
