package openapi

import (
	"net/http"

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

// Mount registers the /openapi.json endpoint on the router.
// The OpenAPI spec is consumed by CI to generate Slate documentation
// which is served at docs.{domain}. No interactive UI is mounted here.
func Mount(r chi.Router, spec *OpenAPISpec) {
	// Serve OpenAPI JSON spec (consumed by Widdershins during doc generation)
	r.Get("/openapi.json", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Header().Set("Access-Control-Allow-Origin", "*")

		specBytes, err := spec.JSON()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		_, _ = w.Write(specBytes)
	})

	// /docs redirects to the Slate documentation site
	r.Get("/docs", func(w http.ResponseWriter, r *http.Request) {
		// Construct docs URL from current host
		// e.g., api.slug.threesix.ai -> docs.slug.threesix.ai
		scheme := "https"
		if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
			scheme = proto
		}

		// Extract the base domain (remove service prefix if present)
		host := r.Host
		docsURL := scheme + "://docs." + host

		http.Redirect(w, r, docsURL, http.StatusTemporaryRedirect)
	})
}
