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"
)

//nolint:gocyclo
func (h *apiHTTPHandler) ListPlayers(
	w http.ResponseWriter,
	r *http.Request,
	_ apimodel.VersionCodePathParam,
	serverKey apimodel.ServerKeyPathParam,
	params apimodel.ListPlayersParams,
) {
	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); 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.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))
}

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
}

func formatListPlayersErrorPath(segments []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 "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 []errorPathSegment) []string {
	if segments[0].model != "ListPlayersParams" {
		return nil
	}

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