package domain_test

import (
	"cmp"
	"fmt"
	"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 TestVillages_Delete(t *testing.T) {
	t.Parallel()

	server := domaintest.NewServer(t)

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

	villages := domain.Villages{
		domaintest.NewVillage(t, func(cfg *domaintest.VillageConfig) {
			cfg.ID = active[0].ID()
			cfg.ServerKey = server.Key()
		}),
		domaintest.NewVillage(t, func(cfg *domaintest.VillageConfig) {
			cfg.ServerKey = server.Key()
		}),
		domaintest.NewVillage(t, func(cfg *domaintest.VillageConfig) {
			cfg.ID = active[1].ID()
			cfg.ServerKey = server.Key()
		}),
		domaintest.NewVillage(t, func(cfg *domaintest.VillageConfig) {
			cfg.ID = active[2].ID()
			cfg.ServerKey = domaintest.RandServerKey()
		}),
	}

	expectedIDs := []int{villages[1].ID()}

	slices.Sort(expectedIDs)

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

	slices.SortFunc(villages, func(a, b domain.Village) int {
		if res := cmp.Compare(a.ServerKey(), b.ServerKey()); res != 0 {
			return res
		}
		return cmp.Compare(a.ID(), b.ID())
	})

	assert.Equal(t, expectedIDs, villages.Delete(server.Key(), active))
}

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

	server := domaintest.NewServer(t)

	villages := domain.BaseVillages{
		domaintest.NewBaseVillage(t),
		domaintest.NewBaseVillage(t),
		domaintest.NewBaseVillage(t),
	}
	slices.SortFunc(villages, func(a, b domain.BaseVillage) int {
		return cmp.Compare(a.ID(), b.ID())
	})

	res, err := domain.NewCreateVillageParams(server.Key(), villages)
	require.NoError(t, err)
	assert.Len(t, res, len(villages))
	for i, v := range villages {
		idx := slices.IndexFunc(res, func(params domain.CreateVillageParams) bool {
			return params.Base().ID() == v.ID() && params.ServerKey() == server.Key()
		})
		require.GreaterOrEqualf(t, idx, 0, "villages[%d] not found", i)

		params := res[idx]

		assert.Equalf(t, v, params.Base(), "villages[%d]", i)
	}
}

func TestListVillagesParams_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 < 0",
			args: args{
				ids: []int{
					domaintest.RandID(),
					domaintest.RandID(),
					domaintest.RandID(),
					-1,
					domaintest.RandID(),
				},
			},
			expectedErr: domain.SliceElementValidationError{
				Model: "ListVillagesParams",
				Field: "ids",
				Index: 3,
				Err: domain.MinGreaterEqualError{
					Min:     0,
					Current: -1,
				},
			},
		},
	}

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

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

			params := domain.NewListVillagesParams()

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

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

	type args struct {
		idGT domain.NullInt
	}

	tests := []struct {
		name        string
		args        args
		expectedErr error
	}{
		{
			name: "OK",
			args: args{
				idGT: domain.NullInt{
					Value: domaintest.RandID(),
					Valid: true,
				},
			},
		},
		{
			name: "ERR: value < 0",
			args: args{
				idGT: domain.NullInt{
					Value: -1,
					Valid: true,
				},
			},
			expectedErr: domain.ValidationError{
				Model: "ListVillagesParams",
				Field: "idGT",
				Err: domain.MinGreaterEqualError{
					Min:     0,
					Current: -1,
				},
			},
		},
	}

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

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

			params := domain.NewListVillagesParams()

			require.ErrorIs(t, params.SetIDGT(tt.args.idGT), tt.expectedErr)
			if tt.expectedErr != nil {
				return
			}
			assert.Equal(t, tt.args.idGT, params.IDGT())
		})
	}
}

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

	type args struct {
		sort []domain.VillageSort
	}

	tests := []struct {
		name        string
		args        args
		expectedErr error
	}{
		{
			name: "OK",
			args: args{
				sort: []domain.VillageSort{
					domain.VillageSortIDASC,
					domain.VillageSortServerKeyASC,
				},
			},
		},
		{
			name: "ERR: len(sort) < 1",
			args: args{
				sort: nil,
			},
			expectedErr: domain.ValidationError{
				Model: "ListVillagesParams",
				Field: "sort",
				Err: domain.LenOutOfRangeError{
					Min:     1,
					Max:     2,
					Current: 0,
				},
			},
		},
		{
			name: "ERR: len(sort) > 2",
			args: args{
				sort: []domain.VillageSort{
					domain.VillageSortIDASC,
					domain.VillageSortServerKeyASC,
					domain.VillageSortServerKeyDESC,
				},
			},
			expectedErr: domain.ValidationError{
				Model: "ListVillagesParams",
				Field: "sort",
				Err: domain.LenOutOfRangeError{
					Min:     1,
					Max:     2,
					Current: 3,
				},
			},
		},
	}

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

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

			params := domain.NewListVillagesParams()

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

func TestListVillagesParams_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.VillageListMaxLimit,
			},
		},
		{
			name: "ERR: limit < 1",
			args: args{
				limit: 0,
			},
			expectedErr: domain.ValidationError{
				Model: "ListVillagesParams",
				Field: "limit",
				Err: domain.MinGreaterEqualError{
					Min:     1,
					Current: 0,
				},
			},
		},
		{
			name: fmt.Sprintf("ERR: limit > %d", domain.VillageListMaxLimit),
			args: args{
				limit: domain.VillageListMaxLimit + 1,
			},
			expectedErr: domain.ValidationError{
				Model: "ListVillagesParams",
				Field: "limit",
				Err: domain.MaxLessEqualError{
					Max:     domain.VillageListMaxLimit,
					Current: domain.VillageListMaxLimit + 1,
				},
			},
		},
	}

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

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

			params := domain.NewListVillagesParams()

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

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

	type args struct {
		offset int
	}

	tests := []struct {
		name        string
		args        args
		expectedErr error
	}{
		{
			name: "OK",
			args: args{
				offset: 100,
			},
		},
		{
			name: "ERR: offset < 0",
			args: args{
				offset: -1,
			},
			expectedErr: domain.ValidationError{
				Model: "ListVillagesParams",
				Field: "offset",
				Err: domain.MinGreaterEqualError{
					Min:     0,
					Current: -1,
				},
			},
		},
	}

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

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

			params := domain.NewListVillagesParams()

			require.ErrorIs(t, params.SetOffset(tt.args.offset), tt.expectedErr)
			if tt.expectedErr != nil {
				return
			}
			assert.Equal(t, tt.args.offset, params.Offset())
		})
	}
}
