package port_test

import (
	"cmp"
	"fmt"
	"net/http"
	"net/http/httptest"
	"slices"
	"strconv"
	"strings"
	"testing"

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

const endpointListVillages = "/v2/versions/%s/servers/%s/villages"

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

	handler := newAPIHTTPHandler(t)
	villages := getAllVillages(t, handler)
	server := villages[0].Server

	tests := []struct {
		name        string
		reqModifier func(t *testing.T, req *http.Request)
		assertResp  func(t *testing.T, req *http.Request, resp *http.Response)
	}{
		{
			name: "OK: without params",
			assertResp: func(t *testing.T, _ *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusOK, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ListVillagesResponse](t, resp.Body)
				assert.Zero(t, body.Cursor.Next)
				assert.NotZero(t, body.Cursor.Self)
				assert.NotZero(t, body.Data)
				assert.True(t, slices.IsSortedFunc(body.Data, func(a, b apimodel.Village) int {
					return cmp.Compare(a.Id, b.Id)
				}))
			},
		},
		{
			name: "OK: limit=1",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("limit", "1")
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusOK, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ListVillagesResponse](t, resp.Body)
				assert.NotZero(t, body.Cursor.Next)
				assert.NotZero(t, body.Cursor.Self)
				assert.NotZero(t, body.Data)
				limit, err := strconv.Atoi(req.URL.Query().Get("limit"))
				require.NoError(t, err)
				assert.Len(t, body.Data, limit)
			},
		},
		{
			name: "OK: limit=1 cursor",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()

				q := req.URL.Query()
				q.Set("limit", "1")
				req.URL.RawQuery = q.Encode()

				resp := doCustomRequest(handler, req.Clone(req.Context()))
				defer resp.Body.Close()
				body := decodeJSON[apimodel.ListVillagesResponse](t, resp.Body)
				require.NotEmpty(t, body.Cursor.Next)

				q.Set("cursor", body.Cursor.Next)
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusOK, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ListVillagesResponse](t, resp.Body)
				assert.Equal(t, req.URL.Query().Get("cursor"), body.Cursor.Self)
				limit, err := strconv.Atoi(req.URL.Query().Get("limit"))
				require.NoError(t, err)
				assert.Len(t, body.Data, limit)
			},
		},
		{
			name: "OK: coords",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()

				q := req.URL.Query()

				for _, v := range villages {
					if v.Server.Key == server.Key {
						q.Add("coords", fmt.Sprintf("%d|%d", v.X, v.Y))
					}

					if len(q["coords"]) == 2 {
						break
					}
				}

				require.NotEmpty(t, q["coords"])

				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusOK, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ListVillagesResponse](t, resp.Body)
				assert.NotZero(t, body.Cursor.Self)
				assert.NotZero(t, body.Data)
				coords := req.URL.Query()["coords"]
				assert.Len(t, body.Data, len(coords))
				for _, v := range body.Data {
					assert.True(t, slices.Contains(coords, fmt.Sprintf("%d|%d", v.X, v.Y)))
				}
			},
		},
		{
			name: "ERR: limit is not an integer",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("limit", "asd")
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code: "invalid-param-format",
							Message: fmt.Sprintf(
								"error binding string parameter: strconv.ParseInt: parsing \"%s\": invalid syntax",
								req.URL.Query().Get("limit"),
							),
							Path: []string{"$query", "limit"},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: limit < 1",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("limit", "0")
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				limit, err := strconv.Atoi(req.URL.Query().Get("limit"))
				require.NoError(t, err)
				domainErr := domain.MinGreaterEqualError{
					Min:     1,
					Current: limit,
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"current": float64(domainErr.Current),
								"min":     float64(domainErr.Min),
							},
							Path: []string{"$query", "limit"},
						},
					},
				}, body)
			},
		},
		{
			name: fmt.Sprintf("ERR: limit > %d", domain.VillageListMaxLimit),
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("limit", strconv.Itoa(domain.VillageListMaxLimit+1))
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				limit, err := strconv.Atoi(req.URL.Query().Get("limit"))
				require.NoError(t, err)
				domainErr := domain.MaxLessEqualError{
					Max:     domain.VillageListMaxLimit,
					Current: limit,
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"current": float64(domainErr.Current),
								"max":     float64(domainErr.Max),
							},
							Path: []string{"$query", "limit"},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: len(cursor) < 1",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("cursor", "")
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				domainErr := domain.LenOutOfRangeError{
					Min:     1,
					Max:     1000,
					Current: len(req.URL.Query().Get("cursor")),
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"current": float64(domainErr.Current),
								"max":     float64(domainErr.Max),
								"min":     float64(domainErr.Min),
							},
							Path: []string{"$query", "cursor"},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: len(cursor) > 1000",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("cursor", gofakeit.LetterN(1001))
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				domainErr := domain.LenOutOfRangeError{
					Min:     1,
					Max:     1000,
					Current: len(req.URL.Query().Get("cursor")),
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"current": float64(domainErr.Current),
								"max":     float64(domainErr.Max),
								"min":     float64(domainErr.Min),
							},
							Path: []string{"$query", "cursor"},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: invalid cursor",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("cursor", gofakeit.LetterN(100))
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, _ *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				var domainErr domain.Error
				require.ErrorAs(t, domain.ErrInvalidCursor, &domainErr)
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Path:    []string{"$query", "cursor"},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: len(coords) > 200",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				for range 201 {
					q.Add("coords", gofakeit.LetterN(50))
				}
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				domainErr := domain.LenOutOfRangeError{
					Min:     0,
					Max:     200,
					Current: len(req.URL.Query()["coords"]),
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"current": float64(domainErr.Current),
								"max":     float64(domainErr.Max),
								"min":     float64(domainErr.Min),
							},
							Path: []string{"$query", "coords"},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: invalid coords string",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("coords", gofakeit.LetterN(100))
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, _ *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				var domainErr domain.Error
				require.ErrorAs(t, domain.ErrInvalidCoordsString, &domainErr)
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Path:    []string{"$query", "coords", "0"},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: version not found",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				req.URL.Path = fmt.Sprintf(endpointListVillages, randInvalidVersionCode(t, handler), server.Key)
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusNotFound, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				pathSegments := strings.Split(req.URL.Path, "/")
				require.Len(t, pathSegments, 7)
				domainErr := domain.VersionNotFoundError{
					VersionCode: pathSegments[3],
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"code": domainErr.VersionCode,
							},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: server not found",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				req.URL.Path = fmt.Sprintf(endpointListVillages, server.Version.Code, domaintest.RandServerKey())
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusNotFound, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				pathSegments := strings.Split(req.URL.Path, "/")
				require.Len(t, pathSegments, 7)
				domainErr := domain.ServerNotFoundError{
					Key: pathSegments[5],
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"key": domainErr.Key,
							},
						},
					},
				}, body)
			},
		},
	}

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

			req := httptest.NewRequest(
				http.MethodGet,
				fmt.Sprintf(endpointListVillages, server.Version.Code, server.Key),
				nil,
			)
			if tt.reqModifier != nil {
				tt.reqModifier(t, req)
			}

			resp := doCustomRequest(handler, req)
			defer resp.Body.Close()
			tt.assertResp(t, req, resp)
		})
	}
}

const endpointListPlayerVillages = "/v2/versions/%s/servers/%s/players/%d/villages"

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

	handler := newAPIHTTPHandler(t)
	villages := getAllVillages(t, handler)

	var server serverWithVersion
	var player apimodel.PlayerMeta
	for _, v := range villages {
		if v.Player != nil {
			player = *v.Player
			server = v.Server
			break
		}
	}

	tests := []struct {
		name        string
		reqModifier func(t *testing.T, req *http.Request)
		assertResp  func(t *testing.T, req *http.Request, resp *http.Response)
	}{
		{
			name: "OK: without params",
			assertResp: func(t *testing.T, _ *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusOK, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ListVillagesResponse](t, resp.Body)
				assert.Zero(t, body.Cursor.Next)
				assert.NotZero(t, body.Cursor.Self)
				assert.NotZero(t, body.Data)
				assert.True(t, slices.IsSortedFunc(body.Data, func(a, b apimodel.Village) int {
					return cmp.Compare(a.Id, b.Id)
				}))
			},
		},
		{
			name: "OK: limit=1",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("limit", "1")
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusOK, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ListVillagesResponse](t, resp.Body)
				assert.NotZero(t, body.Cursor.Next)
				assert.NotZero(t, body.Cursor.Self)
				assert.NotZero(t, body.Data)
				limit, err := strconv.Atoi(req.URL.Query().Get("limit"))
				require.NoError(t, err)
				assert.Len(t, body.Data, limit)
			},
		},
		{
			name: "OK: limit=1 cursor",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()

				q := req.URL.Query()
				q.Set("limit", "1")
				req.URL.RawQuery = q.Encode()

				resp := doCustomRequest(handler, req.Clone(req.Context()))
				defer resp.Body.Close()
				body := decodeJSON[apimodel.ListVillagesResponse](t, resp.Body)
				require.NotEmpty(t, body.Cursor.Next)

				q.Set("cursor", body.Cursor.Next)
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusOK, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ListVillagesResponse](t, resp.Body)
				assert.Equal(t, req.URL.Query().Get("cursor"), body.Cursor.Self)
				limit, err := strconv.Atoi(req.URL.Query().Get("limit"))
				require.NoError(t, err)
				assert.Len(t, body.Data, limit)
			},
		},
		{
			name: "ERR: limit is not an integer",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("limit", "asd")
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code: "invalid-param-format",
							Message: fmt.Sprintf(
								"error binding string parameter: strconv.ParseInt: parsing \"%s\": invalid syntax",
								req.URL.Query().Get("limit"),
							),
							Path: []string{"$query", "limit"},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: limit < 1",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("limit", "0")
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				limit, err := strconv.Atoi(req.URL.Query().Get("limit"))
				require.NoError(t, err)
				domainErr := domain.MinGreaterEqualError{
					Min:     1,
					Current: limit,
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"current": float64(domainErr.Current),
								"min":     float64(domainErr.Min),
							},
							Path: []string{"$query", "limit"},
						},
					},
				}, body)
			},
		},
		{
			name: fmt.Sprintf("ERR: limit > %d", domain.VillageListMaxLimit),
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("limit", strconv.Itoa(domain.VillageListMaxLimit+1))
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				limit, err := strconv.Atoi(req.URL.Query().Get("limit"))
				require.NoError(t, err)
				domainErr := domain.MaxLessEqualError{
					Max:     domain.VillageListMaxLimit,
					Current: limit,
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"current": float64(domainErr.Current),
								"max":     float64(domainErr.Max),
							},
							Path: []string{"$query", "limit"},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: len(cursor) < 1",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("cursor", "")
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				domainErr := domain.LenOutOfRangeError{
					Min:     1,
					Max:     1000,
					Current: len(req.URL.Query().Get("cursor")),
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"current": float64(domainErr.Current),
								"max":     float64(domainErr.Max),
								"min":     float64(domainErr.Min),
							},
							Path: []string{"$query", "cursor"},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: len(cursor) > 1000",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("cursor", gofakeit.LetterN(1001))
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				domainErr := domain.LenOutOfRangeError{
					Min:     1,
					Max:     1000,
					Current: len(req.URL.Query().Get("cursor")),
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"current": float64(domainErr.Current),
								"max":     float64(domainErr.Max),
								"min":     float64(domainErr.Min),
							},
							Path: []string{"$query", "cursor"},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: invalid cursor",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("cursor", gofakeit.LetterN(100))
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, _ *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				var domainErr domain.Error
				require.ErrorAs(t, domain.ErrInvalidCursor, &domainErr)
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Path:    []string{"$query", "cursor"},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: version not found",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				req.URL.Path = fmt.Sprintf(endpointListPlayerVillages, randInvalidVersionCode(t, handler), server.Key, player.Id)
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusNotFound, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				pathSegments := strings.Split(req.URL.Path, "/")
				require.Len(t, pathSegments, 9)
				domainErr := domain.VersionNotFoundError{
					VersionCode: pathSegments[3],
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"code": domainErr.VersionCode,
							},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: server not found",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				req.URL.Path = fmt.Sprintf(endpointListPlayerVillages, server.Version.Code, domaintest.RandServerKey(), player.Id)
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusNotFound, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				pathSegments := strings.Split(req.URL.Path, "/")
				require.Len(t, pathSegments, 9)
				domainErr := domain.ServerNotFoundError{
					Key: pathSegments[5],
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"key": domainErr.Key,
							},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: player not found",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				req.URL.Path = fmt.Sprintf(endpointListPlayerVillages, server.Version.Code, server.Key, domaintest.RandID())
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusNotFound, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				pathSegments := strings.Split(req.URL.Path, "/")
				require.Len(t, pathSegments, 9)
				id, err := strconv.Atoi(pathSegments[7])
				require.NoError(t, err)
				domainErr := domain.PlayerNotFoundError{
					ServerKey: pathSegments[5],
					ID:        id,
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"serverKey": domainErr.ServerKey,
								"id":        float64(id),
							},
						},
					},
				}, body)
			},
		},
	}

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

			req := httptest.NewRequest(
				http.MethodGet,
				fmt.Sprintf(endpointListPlayerVillages, server.Version.Code, server.Key, player.Id),
				nil,
			)
			if tt.reqModifier != nil {
				tt.reqModifier(t, req)
			}

			resp := doCustomRequest(handler, req)
			defer resp.Body.Close()
			tt.assertResp(t, req, resp)
		})
	}
}

const endpointListTribeVillages = "/v2/versions/%s/servers/%s/tribes/%d/villages"

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

	handler := newAPIHTTPHandler(t)
	villages := getAllVillages(t, handler)

	var server serverWithVersion
	var tribe apimodel.TribeMeta
	for _, v := range villages {
		if v.Player != nil && v.Player.Tribe != nil {
			tribe = *v.Player.Tribe
			server = v.Server
			break
		}
	}

	tests := []struct {
		name        string
		reqModifier func(t *testing.T, req *http.Request)
		assertResp  func(t *testing.T, req *http.Request, resp *http.Response)
	}{
		{
			name: "OK: without params",
			assertResp: func(t *testing.T, _ *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusOK, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ListVillagesResponse](t, resp.Body)
				assert.Zero(t, body.Cursor.Next)
				assert.NotZero(t, body.Cursor.Self)
				assert.NotZero(t, body.Data)
				assert.True(t, slices.IsSortedFunc(body.Data, func(a, b apimodel.Village) int {
					return cmp.Compare(a.Id, b.Id)
				}))
			},
		},
		{
			name: "OK: limit=1",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("limit", "1")
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusOK, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ListVillagesResponse](t, resp.Body)
				assert.NotZero(t, body.Cursor.Next)
				assert.NotZero(t, body.Cursor.Self)
				assert.NotZero(t, body.Data)
				limit, err := strconv.Atoi(req.URL.Query().Get("limit"))
				require.NoError(t, err)
				assert.Len(t, body.Data, limit)
			},
		},
		{
			name: "OK: limit=1 cursor",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()

				q := req.URL.Query()
				q.Set("limit", "1")
				req.URL.RawQuery = q.Encode()

				resp := doCustomRequest(handler, req.Clone(req.Context()))
				defer resp.Body.Close()
				body := decodeJSON[apimodel.ListVillagesResponse](t, resp.Body)
				require.NotEmpty(t, body.Cursor.Next)

				q.Set("cursor", body.Cursor.Next)
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusOK, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ListVillagesResponse](t, resp.Body)
				assert.Equal(t, req.URL.Query().Get("cursor"), body.Cursor.Self)
				limit, err := strconv.Atoi(req.URL.Query().Get("limit"))
				require.NoError(t, err)
				assert.Len(t, body.Data, limit)
			},
		},
		{
			name: "ERR: limit is not an integer",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("limit", "asd")
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code: "invalid-param-format",
							Message: fmt.Sprintf(
								"error binding string parameter: strconv.ParseInt: parsing \"%s\": invalid syntax",
								req.URL.Query().Get("limit"),
							),
							Path: []string{"$query", "limit"},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: limit < 1",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("limit", "0")
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				limit, err := strconv.Atoi(req.URL.Query().Get("limit"))
				require.NoError(t, err)
				domainErr := domain.MinGreaterEqualError{
					Min:     1,
					Current: limit,
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"current": float64(domainErr.Current),
								"min":     float64(domainErr.Min),
							},
							Path: []string{"$query", "limit"},
						},
					},
				}, body)
			},
		},
		{
			name: fmt.Sprintf("ERR: limit > %d", domain.VillageListMaxLimit),
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("limit", strconv.Itoa(domain.VillageListMaxLimit+1))
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				limit, err := strconv.Atoi(req.URL.Query().Get("limit"))
				require.NoError(t, err)
				domainErr := domain.MaxLessEqualError{
					Max:     domain.VillageListMaxLimit,
					Current: limit,
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"current": float64(domainErr.Current),
								"max":     float64(domainErr.Max),
							},
							Path: []string{"$query", "limit"},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: len(cursor) < 1",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("cursor", "")
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				domainErr := domain.LenOutOfRangeError{
					Min:     1,
					Max:     1000,
					Current: len(req.URL.Query().Get("cursor")),
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"current": float64(domainErr.Current),
								"max":     float64(domainErr.Max),
								"min":     float64(domainErr.Min),
							},
							Path: []string{"$query", "cursor"},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: len(cursor) > 1000",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("cursor", gofakeit.LetterN(1001))
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				domainErr := domain.LenOutOfRangeError{
					Min:     1,
					Max:     1000,
					Current: len(req.URL.Query().Get("cursor")),
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"current": float64(domainErr.Current),
								"max":     float64(domainErr.Max),
								"min":     float64(domainErr.Min),
							},
							Path: []string{"$query", "cursor"},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: invalid cursor",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				q := req.URL.Query()
				q.Set("cursor", gofakeit.LetterN(100))
				req.URL.RawQuery = q.Encode()
			},
			assertResp: func(t *testing.T, _ *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				var domainErr domain.Error
				require.ErrorAs(t, domain.ErrInvalidCursor, &domainErr)
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Path:    []string{"$query", "cursor"},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: version not found",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				req.URL.Path = fmt.Sprintf(endpointListTribeVillages, randInvalidVersionCode(t, handler), server.Key, tribe.Id)
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusNotFound, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				pathSegments := strings.Split(req.URL.Path, "/")
				require.Len(t, pathSegments, 9)
				domainErr := domain.VersionNotFoundError{
					VersionCode: pathSegments[3],
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"code": domainErr.VersionCode,
							},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: server not found",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				req.URL.Path = fmt.Sprintf(endpointListTribeVillages, server.Version.Code, domaintest.RandServerKey(), tribe.Id)
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusNotFound, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				pathSegments := strings.Split(req.URL.Path, "/")
				require.Len(t, pathSegments, 9)
				domainErr := domain.ServerNotFoundError{
					Key: pathSegments[5],
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"key": domainErr.Key,
							},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: tribe not found",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				req.URL.Path = fmt.Sprintf(endpointListTribeVillages, server.Version.Code, server.Key, domaintest.RandID())
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusNotFound, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				pathSegments := strings.Split(req.URL.Path, "/")
				require.Len(t, pathSegments, 9)
				id, err := strconv.Atoi(pathSegments[7])
				require.NoError(t, err)
				domainErr := domain.TribeNotFoundError{
					ServerKey: pathSegments[5],
					ID:        id,
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"serverKey": domainErr.ServerKey,
								"id":        float64(id),
							},
						},
					},
				}, body)
			},
		},
	}

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

			req := httptest.NewRequest(
				http.MethodGet,
				fmt.Sprintf(endpointListTribeVillages, server.Version.Code, server.Key, tribe.Id),
				nil,
			)
			if tt.reqModifier != nil {
				tt.reqModifier(t, req)
			}

			resp := doCustomRequest(handler, req)
			defer resp.Body.Close()
			tt.assertResp(t, req, resp)
		})
	}
}

const endpointGetVillage = "/v2/versions/%s/servers/%s/villages/%d"

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

	handler := newAPIHTTPHandler(t)
	village := randSliceElement(getAllVillages(t, handler))

	tests := []struct {
		name        string
		reqModifier func(t *testing.T, req *http.Request)
		assertResp  func(t *testing.T, req *http.Request, resp *http.Response)
	}{
		{
			name: "OK",
			assertResp: func(t *testing.T, _ *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusOK, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.GetVillageResponse](t, resp.Body)
				assert.Equal(t, village.Village, body.Data)
			},
		},
		{
			name: "ERR: id < 1",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				req.URL.Path = fmt.Sprintf(
					endpointGetVillage,
					village.Server.Version.Code,
					village.Server.Key,
					domaintest.RandID()*-1,
				)
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				pathSegments := strings.Split(req.URL.Path, "/")
				require.Len(t, pathSegments, 8)
				id, err := strconv.Atoi(pathSegments[7])
				require.NoError(t, err)
				domainErr := domain.MinGreaterEqualError{
					Min:     1,
					Current: id,
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"min":     float64(domainErr.Min),
								"current": float64(domainErr.Current),
							},
							Path: []string{"$path", "villageId"},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: version not found",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				req.URL.Path = fmt.Sprintf(endpointGetVillage, randInvalidVersionCode(t, handler), village.Server.Key, village.Id)
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusNotFound, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				pathSegments := strings.Split(req.URL.Path, "/")
				require.Len(t, pathSegments, 8)
				domainErr := domain.VersionNotFoundError{
					VersionCode: pathSegments[3],
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"code": domainErr.VersionCode,
							},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: server not found",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				req.URL.Path = fmt.Sprintf(endpointGetVillage, village.Server.Version.Code, domaintest.RandServerKey(), village.Id)
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusNotFound, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				pathSegments := strings.Split(req.URL.Path, "/")
				require.Len(t, pathSegments, 8)
				domainErr := domain.ServerNotFoundError{
					Key: pathSegments[5],
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"key": domainErr.Key,
							},
						},
					},
				}, body)
			},
		},
		{
			name: "ERR: village not found",
			reqModifier: func(t *testing.T, req *http.Request) {
				t.Helper()
				req.URL.Path = fmt.Sprintf(
					endpointGetVillage,
					village.Server.Version.Code,
					village.Server.Key,
					domaintest.RandID(),
				)
			},
			assertResp: func(t *testing.T, req *http.Request, resp *http.Response) {
				t.Helper()

				assert.Equal(t, http.StatusNotFound, resp.StatusCode)

				// body
				body := decodeJSON[apimodel.ErrorResponse](t, resp.Body)
				pathSegments := strings.Split(req.URL.Path, "/")
				require.Len(t, pathSegments, 8)
				id, err := strconv.Atoi(pathSegments[7])
				require.NoError(t, err)
				domainErr := domain.VillageNotFoundError{
					ID:        id,
					ServerKey: pathSegments[5],
				}
				assert.Equal(t, apimodel.ErrorResponse{
					Errors: []apimodel.Error{
						{
							Code:    apimodel.ErrorCode(domainErr.Code()),
							Message: domainErr.Error(),
							Params: map[string]any{
								"id":        float64(domainErr.ID),
								"serverKey": domainErr.ServerKey,
							},
						},
					},
				}, body)
			},
		},
	}

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

			req := httptest.NewRequest(
				http.MethodGet,
				fmt.Sprintf(endpointGetVillage, village.Server.Version.Code, village.Server.Key, village.Id),
				nil,
			)
			if tt.reqModifier != nil {
				tt.reqModifier(t, req)
			}

			resp := doCustomRequest(handler, req)
			defer resp.Body.Close()
			tt.assertResp(t, req, resp)
		})
	}
}

type villageWithServer struct {
	apimodel.Village
	Server serverWithVersion
}

func getAllVillages(tb testing.TB, h http.Handler) []villageWithServer {
	tb.Helper()

	servers := getAllServers(tb, h)

	var villages []villageWithServer

	for _, s := range servers {
		resp := doRequest(h, http.MethodGet, fmt.Sprintf(endpointListVillages, s.Version.Code, s.Key), nil)
		require.Equal(tb, http.StatusOK, resp.StatusCode)

		for _, v := range decodeJSON[apimodel.ListVillagesResponse](tb, resp.Body).Data {
			villages = append(villages, villageWithServer{
				Village: v,
				Server:  s,
			})
		}

		_ = resp.Body.Close()
	}

	require.NotZero(tb, villages)

	return villages
}
