package port

import (
	"net/http"
	"strconv"

	"gitea.dwysokinski.me/twhelp/corev3/internal/domain"
	"gitea.dwysokinski.me/twhelp/corev3/internal/port/internal/apimodel"
)

func (h *apiHTTPHandler) ListVillages(
	w http.ResponseWriter,
	r *http.Request,
	_ apimodel.VersionCodePathParam,
	serverKey apimodel.ServerKeyPathParam,
	params apimodel.ListVillagesParams,
) {
	domainParams := domain.NewListVillagesParams()

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

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

	if params.Coords != nil {
		if err := domainParams.SetCoordsString(*params.Coords); err != nil {
			h.errorRenderer.withErrorPathFormatter(formatListVillagesErrorPath).render(w, r, err)
			return
		}
	}

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

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

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

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

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

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