package pulls

import (
	"net/http"

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

func (s *Pulls) Router(mw *middleware.Middleware) http.Handler {
	r := chi.NewRouter()
	r.With(middleware.Paginate).Get("/", s.RepoPulls)
	r.Get("/pipeline-statuses", pipelines.StatusesHandler(s.oauth, s.repoResolver, s.pages, s.logger))
	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
		r.Get("/{version}/_/actions", s.PullActions)

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

		r.Group(func(r chi.Router) {
			r.Use(middleware.AuthMiddleware(s.oauth))
			r.Get("/edit", s.EditPull)
			r.Post("/edit", s.EditPull)
			r.Post("/resubmit", s.ResubmitPull)
			r.Post("/close", s.ClosePull)
			r.Post("/reopen", s.ReopenPull)
			r.Post("/subscribe", s.SubscribePull)
			// 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

}
