package httpapi

import (
	"net/http"

	"github.com/ashie/gosearch/internal/search"
)

type Handler struct {
	searchSvc *search.Service
}

func NewHandler(searchSvc *search.Service) *Handler {
	return &Handler{searchSvc: searchSvc}
}

func (h *Handler) Healthz(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte("OK"))
}

func (h *Handler) Search(w http.ResponseWriter, r *http.Request) {
	req, err := search.ParseSearchRequest(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	resp, err := h.searchSvc.Search(r.Context(), req)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err := search.WriteSearchResponse(w, req.Format, resp); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}

