// Package apidocs serves the interactive API reference (Scalar) and the raw
// OpenAPI contract consumed by the Vue frontend.
package apidocs

import (
	"embed"
	"net/http"
	"os"
)

//go:embed api-reference.html
var referenceFS embed.FS

// ReferenceHandler serves the Scalar API reference page.
func ReferenceHandler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		if r.Method == http.MethodHead {
			w.WriteHeader(http.StatusOK)
			return
		}
		b, err := referenceFS.ReadFile("api-reference.html")
		if err != nil {
			http.Error(w, "docs unavailable", http.StatusInternalServerError)
			return
		}
		_, _ = w.Write(b)
	}
}

// OpenAPIFile serves the OpenAPI document from disk. path is the file location
// (config.OpenAPIPath; default docs/openapi.yaml so docs/openapi.yaml stays
// the single source of truth).
func OpenAPIFile(path string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "*")
		if r.Method == http.MethodOptions {
			w.WriteHeader(http.StatusNoContent)
			return
		}
		b, err := os.ReadFile(path)
		if err != nil {
			http.Error(w, "openapi.yaml not found", http.StatusNotFound)
			return
		}
		w.Header().Set("Content-Type", "application/yaml; charset=utf-8")
		if r.Method == http.MethodHead {
			w.WriteHeader(http.StatusOK)
			return
		}
		_, _ = w.Write(b)
	}
}


