package api

import (
	"encoding/json"
	"net/http"

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

type ApiHandler struct {
	sources   SourcesImpl
	copyright CopyrightImpl
	patch     PatchImpl
}

func NewApi(
	sources SourcesImpl,
	copyright CopyrightImpl,
	patch PatchImpl,
) *ApiHandler {
	return &ApiHandler{
		sources:   sources,
		copyright: copyright,
		patch:     patch,
	}
}

func returnJson[REQ any, RESP any](w http.ResponseWriter, req REQ, fn func(REQ) (RESP, error)) {
	resp, err := fn(req)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	ans, err := json.Marshal(resp)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Write(ans)
}

type PingResp struct {
	HttpCode   int    `json:"http_status_code"`
	LastUpdate string `json:"last_update"`
	Status     string `json:"status"`
}

type NamedItem struct {
	Name string `json:"name"`
}

func (a *ApiHandler) Route(r chi.Router) {
	r.Route("/api", a.RouteSource)
	r.Route("/copyright/api", a.RouteCopyright)
	r.Route("/patches/api", a.RoutePatch)
}
