package port

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

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

func (h *apiHTTPHandler) ListVersions(w http.ResponseWriter, r *http.Request, params apimodel.ListVersionsParams) {
	domainParams := domain.NewListVersionsParams()

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

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

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

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

func (h *apiHTTPHandler) GetVersion(w http.ResponseWriter, r *http.Request, _ apimodel.VersionCodePathParam) {
	version, _ := versionFromContext(r.Context())
	renderJSON(w, r, http.StatusOK, apimodel.NewGetVersionResponse(version))
}

func (h *apiHTTPHandler) versionMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		routeCtx := chi.RouteContext(ctx)
		idx := slices.Index(routeCtx.URLParams.Keys, "versionCode")

		if idx < 0 {
			next.ServeHTTP(w, r)
			return
		}

		version, err := h.versionSvc.Get(ctx, routeCtx.URLParams.Values[idx])
		if err != nil {
			h.errorRenderer.render(w, r, err)
			return
		}

		next.ServeHTTP(w, r.WithContext(versionToContext(ctx, version)))
	})
}

type versionCtxKey struct{}

func versionToContext(ctx context.Context, v domain.Version) context.Context {
	return context.WithValue(ctx, versionCtxKey{}, v)
}

func versionFromContext(ctx context.Context) (domain.Version, bool) {
	v, ok := ctx.Value(versionCtxKey{}).(domain.Version)
	return v, ok
}

func formatListVersionsErrorPath(segments []errorPathSegment) []string {
	if segments[0].model != "ListVersionsParams" {
		return nil
	}

	switch segments[0].field {
	case "cursor":
		return []string{"$query", "cursor"}
	case "limit":
		return []string{"$query", "limit"}
	default:
		return nil
	}
}
