package server

import (
	"html/template"
	"net/http"

	"gitlab.com/Timfa/bluegit/internal/cispec"
	"gitlab.com/Timfa/bluegit/internal/i18n"
	"gitlab.com/Timfa/bluegit/internal/images"
	"gitlab.com/Timfa/bluegit/internal/webhook"
)

func (s *Server) infoPage(w http.ResponseWriter, r *http.Request) {
	doc, raw, err := s.ciDocument(s.langOf(r))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	v := s.view(w, r, "title.info")
	v.Page = "info"
	v.Info = true
	v.Spec = doc
	v.SpecJSON = template.JS(raw)
	v.APIJSON = template.JS(apiIndex())
	v.HookDoc = webhook.Example()
	v.IssueDoc = webhook.IssueExample()
	s.attachUpdate(&v, s.langOf(r))
	s.render(w, "info", v)
}

func (s *Server) webhookSpec(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Header().Set("Cache-Control", "no-store")
	_, _ = w.Write(webhook.OpenAPI())
}

func (s *Server) ciSpec(w http.ResponseWriter, r *http.Request) {
	lang := i18n.EN
	if q := r.URL.Query().Get("lang"); q != "" {
		lang = i18n.Parse(q)
	}
	_, raw, err := s.ciDocument(lang)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Header().Set("Cache-Control", "no-store")
	_, _ = w.Write(raw)
}

func (s *Server) ciDocument(lang i18n.Lang) (cispec.Doc, []byte, error) {
	set, err := images.Effective(s.Cfg.CI.ImageOverrides())
	if err != nil {
		return cispec.Doc{}, nil, err
	}
	doc := cispec.Build(lang, set)
	return doc, cispec.Marshal(doc), nil
}
