package openapi

import (
	"fmt"
	"net/http"

	"github.com/go-chi/chi/v5"
	scalargo "github.com/bdpiprava/scalar-go"
)

// Mount registers /docs and /openapi.json endpoints on the router.
func Mount(r chi.Router, spec *OpenAPISpec) {
	// Serve OpenAPI JSON
	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)
	})

	// Serve Scalar docs UI
	r.Get("/docs", func(w http.ResponseWriter, r *http.Request) {
		scheme := "http"
		if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
			scheme = proto
		} else if r.TLS != nil {
			scheme = "https"
		}
		specURL := fmt.Sprintf("%s://%s/openapi.json", scheme, r.Host)

		html, err := scalargo.NewV2(
			scalargo.WithSpecURL(specURL),
			scalargo.WithDarkMode(),
		)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		_, _ = fmt.Fprint(w, html)
	})
}
