package port

import (
	"context"
	"net/http"
	"slices"
	"strconv"

	"gitea.dwysokinski.me/twhelp/corev3/internal/domain"
	"gitea.dwysokinski.me/twhelp/corev3/internal/port/internal/apimodel"
	"github.com/go-chi/chi/v5"
)

const apiPlayerSortMaxLength = 2

var apiPlayerSortAllowedValues = []domain.PlayerSort{
	domain.PlayerSortODScoreAttASC,
	domain.PlayerSortODScoreAttDESC,
	domain.PlayerSortODScoreDefASC,
	domain.PlayerSortODScoreDefDESC,
	domain.PlayerSortODScoreSupASC,
	domain.PlayerSortODScoreSupDESC,
	domain.PlayerSortODScoreTotalASC,
	domain.PlayerSortODScoreTotalDESC,
	domain.PlayerSortPointsASC,
	domain.PlayerSortPointsDESC,
	domain.PlayerSortDeletedAtASC,
	domain.PlayerSortDeletedAtDESC,
}

//nolint:gocyclo
func (h *apiHTTPHandler) ListVersionPlayers(
	w http.ResponseWriter,
	r *http.Request,
	versionCode apimodel.VersionCodePathParam,
	params apimodel.ListVersionPlayersParams,
) {
	domainParams := domain.NewListPlayersParams()

	if err := domainParams.SetSort([]domain.PlayerSort{domain.PlayerSortIDASC}); err != nil {
		h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
		return
	}

	if params.Sort != nil {
		if err := domainParams.PrependSortString(
			*params.Sort,
			apiPlayerSortAllowedValues,
			apiPlayerSortMaxLength,
		); err != nil {
			h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
			return
		}
	}

	if err := domainParams.PrependSort([]domain.PlayerSort{domain.PlayerSortServerKeyASC}); err != nil {
		h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
		return
	}

	if err := domainParams.SetVersionCodes([]string{versionCode}); err != nil {
		h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
		return
	}

	if params.Id != nil {
		if err := domainParams.SetIDs(*params.Id); err != nil {
			h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
			return
		}
	}

	if params.Name != nil {
		if err := domainParams.SetNames(*params.Name); err != nil {
			h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
			return
		}
	}

	if params.Deleted != nil {
		if err := domainParams.SetDeleted(domain.NullBool{
			V:     *params.Deleted,
			Valid: true,
		}); err != nil {
			h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
			return
		}
	}

	if params.Limit != nil {
		if err := domainParams.SetLimit(*params.Limit); err != nil {
			h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
			return
		}
	}

	if params.Cursor != nil {
		if err := domainParams.SetEncodedCursor(*params.Cursor); err != nil {
			h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
			return
		}
	}

	res, err := h.playerSvc.ListWithRelations(r.Context(), domainParams)
	if err != nil {
		h.errorRenderer.render(w, r, err)
		return
	}

	renderJSON(w, r, http.StatusOK, apimodel.NewListPlayersWithServersResponse(res))
}

//nolint:gocyclo
func (h *apiHTTPHandler) ListServerPlayers(
	w http.ResponseWriter,
	r *http.Request,
	_ apimodel.VersionCodePathParam,
	serverKey apimodel.ServerKeyPathParam,
	params apimodel.ListServerPlayersParams,
) {
	domainParams := domain.NewListPlayersParams()

	if err := domainParams.SetSort([]domain.PlayerSort{domain.PlayerSortIDASC}); err != nil {
		h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
		return
	}

	if params.Sort != nil {
		if err := domainParams.PrependSortString(
			*params.Sort,
			apiPlayerSortAllowedValues,
			apiPlayerSortMaxLength,
		); err != nil {
			h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
			return
		}
	}

	if err := domainParams.SetServerKeys([]string{serverKey}); err != nil {
		h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
		return
	}

	if params.Id != nil {
		if err := domainParams.SetIDs(*params.Id); err != nil {
			h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
			return
		}
	}

	if params.Name != nil {
		if err := domainParams.SetNames(*params.Name); err != nil {
			h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
			return
		}
	}

	if params.Deleted != nil {
		if err := domainParams.SetDeleted(domain.NullBool{
			V:     *params.Deleted,
			Valid: true,
		}); err != nil {
			h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
			return
		}
	}

	if params.Limit != nil {
		if err := domainParams.SetLimit(*params.Limit); err != nil {
			h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
			return
		}
	}

	if params.Cursor != nil {
		if err := domainParams.SetEncodedCursor(*params.Cursor); err != nil {
			h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
			return
		}
	}

	res, err := h.playerSvc.ListWithRelations(r.Context(), domainParams)
	if err != nil {
		h.errorRenderer.render(w, r, err)
		return
	}

	renderJSON(w, r, http.StatusOK, apimodel.NewListPlayersResponse(res))
}

//nolint:gocyclo
func (h *apiHTTPHandler) ListTribeMembers(
	w http.ResponseWriter,
	r *http.Request,
	_ apimodel.VersionCodePathParam,
	serverKey apimodel.ServerKeyPathParam,
	tribeID apimodel.TribeIdPathParam,
	params apimodel.ListTribeMembersParams,
) {
	domainParams := domain.NewListPlayersParams()

	if err := domainParams.SetSort([]domain.PlayerSort{domain.PlayerSortIDASC}); err != nil {
		h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
		return
	}

	if params.Sort != nil {
		if err := domainParams.PrependSortString(
			*params.Sort,
			apiPlayerSortAllowedValues,
			apiPlayerSortMaxLength,
		); err != nil {
			h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
			return
		}
	}

	if err := domainParams.SetServerKeys([]string{serverKey}); err != nil {
		h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
		return
	}

	if err := domainParams.SetTribeIDs([]int{tribeID}); err != nil {
		h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
		return
	}

	if params.Limit != nil {
		if err := domainParams.SetLimit(*params.Limit); err != nil {
			h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
			return
		}
	}

	if params.Cursor != nil {
		if err := domainParams.SetEncodedCursor(*params.Cursor); err != nil {
			h.errorRenderer.withErrorPathFormatter(formatListPlayersErrorPath).render(w, r, err)
			return
		}
	}

	res, err := h.playerSvc.ListWithRelations(r.Context(), domainParams)
	if err != nil {
		h.errorRenderer.render(w, r, err)
		return
	}

	renderJSON(w, r, http.StatusOK, apimodel.NewListPlayersResponse(res))
}

func (h *apiHTTPHandler) GetPlayer(
	w http.ResponseWriter,
	r *http.Request,
	_ apimodel.VersionCodePathParam,
	_ apimodel.ServerKeyPathParam,
	_ apimodel.PlayerIdPathParam,
) {
	player, _ := playerFromContext(r.Context())
	renderJSON(w, r, http.StatusOK, apimodel.NewGetPlayerResponse(player))
}

func (h *apiHTTPHandler) playerMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		routeCtx := chi.RouteContext(ctx)
		server, serverOK := serverFromContext(ctx)
		playerIDIdx := slices.Index(routeCtx.URLParams.Keys, "playerId")

		if !serverOK || playerIDIdx < 0 {
			next.ServeHTTP(w, r)
			return
		}

		playerID, err := strconv.Atoi(routeCtx.URLParams.Values[playerIDIdx])
		if err != nil {
			return
		}

		player, err := h.playerSvc.GetWithRelations(
			ctx,
			playerID,
			server.Key(),
		)
		if err != nil {
			h.errorRenderer.withErrorPathFormatter(formatGetPlayerErrorPath).render(w, r, err)
			return
		}

		next.ServeHTTP(w, r.WithContext(playerToContext(ctx, player)))
	})
}

type playerCtxKey struct{}

func playerToContext(ctx context.Context, p domain.PlayerWithRelations) context.Context {
	return context.WithValue(ctx, playerCtxKey{}, p)
}

func playerFromContext(ctx context.Context) (domain.PlayerWithRelations, bool) {
	p, ok := ctx.Value(playerCtxKey{}).(domain.PlayerWithRelations)
	return p, ok
}

//nolint:gocyclo
func formatListPlayersErrorPath(segments []domain.ErrorPathSegment) []string {
	if segments[0].Model != "ListPlayersParams" {
		return nil
	}

	switch segments[0].Field {
	case "cursor":
		return []string{"$query", "cursor"}
	case "limit":
		return []string{"$query", "limit"}
	case "deleted":
		return []string{"$query", "deleted"}
	case "names":
		path := []string{"$query", "name"}
		if segments[0].Index >= 0 {
			path = append(path, strconv.Itoa(segments[0].Index))
		}
		return path
	case "ids":
		path := []string{"$query", "id"}
		if segments[0].Index >= 0 {
			path = append(path, strconv.Itoa(segments[0].Index))
		}
		return path
	case "sort":
		path := []string{"$query", "sort"}
		if segments[0].Index >= 0 {
			path = append(path, strconv.Itoa(segments[0].Index))
		}
		return path
	default:
		return nil
	}
}

func formatGetPlayerErrorPath(segments []domain.ErrorPathSegment) []string {
	if segments[0].Model != "ListPlayersParams" {
		return nil
	}

	switch segments[0].Field {
	case "ids":
		return []string{"$path", "playerId"}
	default:
		return nil
	}
}
