package server

import (
	"net/http"

	"github.com/go-chi/chi/v5"
)

// NewRouter builds the chi router with all OCI Distribution Spec
// endpoints and auth middleware wired up. If ociRouter is non-nil,
// its routes are mounted under /v2 behind the auth middleware.
func NewRouter(validator TokenValidator, loginClient LoginClient, serviceName string, ociRouter http.Handler) *chi.Mux {
	r := chi.NewRouter()

	// Token endpoint is NOT behind RequireAuth — clients use Basic auth
	// here to obtain a bearer token.
	r.Get("/v2/token", TokenHandler(loginClient, validator))

	// All other /v2 endpoints require a valid bearer token.
	r.Route("/v2", func(v2 chi.Router) {
		v2.Use(RequireAuth(validator, serviceName))
		v2.Get("/", V2Handler())
		if ociRouter != nil {
			v2.Mount("/", ociRouter)
		}
	})

	return r
}
