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) ListTribes(
	w http.ResponseWriter,
	r *http.Request,
	_ apimodel.VersionCodePathParam,
	serverKey apimodel.ServerKeyPathParam,
	params apimodel.ListTribesParams,
) {
	domainParams := domain.NewListTribesParams()

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

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

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

	if params.Tag != nil {
		if err := domainParams.SetTags(*params.Tag); err != nil {
			h.errorRenderer.withErrorPathFormatter(formatListTribesErrorPath).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(formatListTribesErrorPath).render(w, r, err)
			return
		}
	}

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

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

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

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

func (h *apiHTTPHandler) GetTribe(
	w http.ResponseWriter,
	r *http.Request,
	_ apimodel.VersionCodePathParam,
	_ apimodel.ServerKeyPathParam,
	_ apimodel.TribeIdPathParam,
) {
	tribe, _ := tribeFromContext(r.Context())
	renderJSON(w, r, http.StatusOK, apimodel.NewGetTribeResponse(tribe))
}

func (h *apiHTTPHandler) tribeMiddleware(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)
		tribeIDIdx := slices.Index(routeCtx.URLParams.Keys, "tribeId")

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

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

		tribe, err := h.tribeSvc.Get(
			ctx,
			tribeID,
			server.Key(),
		)
		if err != nil {
			h.errorRenderer.withErrorPathFormatter(formatGetTribeErrorPath).render(w, r, err)
			return
		}

		next.ServeHTTP(w, r.WithContext(tribeToContext(ctx, tribe)))
	})
}

type tribeCtxKey struct{}

func tribeToContext(ctx context.Context, t domain.Tribe) context.Context {
	return context.WithValue(ctx, tribeCtxKey{}, t)
}

func tribeFromContext(ctx context.Context) (domain.Tribe, bool) {
	t, ok := ctx.Value(tribeCtxKey{}).(domain.Tribe)
	return t, ok
}

func formatListTribesErrorPath(segments []errorPathSegment) []string {
	if segments[0].model != "ListTribesParams" {
		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 "tags":
		return []string{"$query", "tag"}
	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 formatGetTribeErrorPath(segments []errorPathSegment) []string {
	if segments[0].model != "ListTribesParams" {
		return nil
	}

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