package api

import (
	_ "embed"
	"encoding/json"
	"net/http"
	"sync"

	"github.com/gin-gonic/gin"
	"gopkg.in/yaml.v3"
)

//go:embed openapi/spec.yaml
var openAPISpecYAML []byte

//go:embed openapi/docs.html
var openAPIDocsHTML []byte

var (
	openAPIJSONOnce sync.Once
	openAPIJSON     []byte
	openAPIJSONErr  error
)

func loadOpenAPIJSON() {
	var doc any
	if err := yaml.Unmarshal(openAPISpecYAML, &doc); err != nil {
		openAPIJSONErr = err
		return
	}
	openAPIJSON, openAPIJSONErr = json.Marshal(doc)
}

func (s *Server) serveOpenAPIJSON(c *gin.Context) {
	openAPIJSONOnce.Do(loadOpenAPIJSON)
	if openAPIJSONErr != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": openAPIJSONErr.Error()})
		return
	}
	c.Header("Cache-Control", "public, max-age=300")
	c.Data(http.StatusOK, "application/json; charset=utf-8", openAPIJSON)
}

func (s *Server) serveOpenAPIYAML(c *gin.Context) {
	c.Header("Cache-Control", "public, max-age=300")
	c.Data(http.StatusOK, "application/yaml; charset=utf-8", openAPISpecYAML)
}

func (s *Server) serveOpenAPIDocs(c *gin.Context) {
	c.Data(http.StatusOK, "text/html; charset=utf-8", openAPIDocsHTML)
}
