package pulls

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

	"github.com/go-chi/chi/v5"
	"tangled.org/core/appview/db"
	"tangled.org/core/orm"
)

// middleware that is tacked on top of /{user}/{repo}/pulls/{pull}
func (s *Pulls) ResolvePullMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		l := s.logger.With("middleware", "ResolvePullMiddleware")
		f, err := s.repoResolver.Resolve(r)
		if err != nil {
			l.Error("failed to fully resolve repo", "err", err)
			w.WriteHeader(http.StatusNotFound)
			s.pages.ErrorKnot404(w)
			return
		}

		prId, err := strconv.Atoi(chi.URLParam(r, "pull"))
		if err != nil {
			l.Debug("failed to parse pr id", "err", err)
			w.WriteHeader(http.StatusNotFound)
			s.pages.Error404(w)
			return
		}

		pr, err := db.GetPull(r.Context(), s.db, orm.FilterEq("repo_did", f.RepoDid), orm.FilterEq("pull_id", prId))
		if err != nil {
			l.Debug("failed to query PR", "err", err)
			w.WriteHeader(http.StatusNotFound)
			s.pages.Error404(w)
			return
		}

		ctx := context.WithValue(r.Context(), "pull", pr)

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