package pulls

import (
	"net/http"

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

func (s *Pulls) Router(mw *middleware.Middleware) http.Handler {
	r := chi.NewRouter()
	r.With(middleware.Paginate).Get("/", s.RepoPulls)
	r.With(middleware.AuthMiddleware(s.oauth)).Route("/new", func(r chi.Router) {
		r.Get("/", s.NewPull)
		r.Post("/", s.NewPull)
		r.Post("/refresh", s.RefreshCompose) // TODO: remove this. we just have to refresh source & review steps
	})
	r.Get("/_/composediff", s.PullComposeDiffFragment)

	r.Route("/{pull}", func(r chi.Router) {
		r.Use(s.ResolvePullMiddleware)
		r.Get("/opengraph", s.PullOpenGraphSummary)

		// PR routes
		r.Get("/", s.RedirectLatestVersion)
		r.Get("/{version}", s.PullSingle)
		r.Get("/{version}/{revspec}", s.PullSingle)
		r.Get("/{version}.patch", s.PullPatchRaw)

		// htmx fragments
		// TODO: remove this later. HTMX should not be used for static elements
		r.Get("/{version}/_/actions", s.PullActions)
		r.Get("/{version}/_/comment", s.PullComment)

		r.Get("/diff", s.PullDiffFragment)
		r.Get("/interdiff", s.PullInterdiffFragment)

		r.Group(func(r chi.Router) {
			r.Use(middleware.AuthMiddleware(s.oauth))
			r.Post("/resubmit", s.ResubmitPull)
			r.Post("/close", s.ClosePull)
			r.Post("/reopen", s.ReopenPull)

			// collaborators only
			r.Group(func(r chi.Router) {
				r.Use(mw.RepoPermissionMiddleware("repo:push"))
				r.Post("/merge", s.MergePull)
				// maybe lock, etc.
			})

			r.Group(func(r chi.Router) {
				r.Use(mw.RepoPermissionMiddleware("repo:push"))
				r.Post("/trigger-ci", s.TriggerCi)
			})
		})
	})

	return r

}
