package handler import ( "net/http" "strconv" "github.com/go-chi/chi/v5" "github.com/prabhupadasays/spsays-bff/internal/repository" "github.com/prabhupadasays/spsays-bff/pkg/response" ) type LetterHandler struct { repo *repository.LetterRepo } func NewLetterHandler(repo *repository.LetterRepo) *LetterHandler { return &LetterHandler{repo: repo} } func (h *LetterHandler) GetBySlug(w http.ResponseWriter, r *http.Request) { slug := chi.URLParam(r, "slug") doc, err := h.repo.GetBySlug(r.Context(), slug) if err != nil { response.Error(w, http.StatusInternalServerError, "failed to fetch letter") return } if doc == nil { response.Error(w, http.StatusNotFound, "letter not found") return } response.JSON(w, http.StatusOK, doc) } func (h *LetterHandler) GetByYear(w http.ResponseWriter, r *http.Request) { yearStr := chi.URLParam(r, "year") year, err := strconv.Atoi(yearStr) if err != nil { response.Error(w, http.StatusBadRequest, "invalid year") return } docs, err := h.repo.GetByYear(r.Context(), year) if err != nil { response.Error(w, http.StatusInternalServerError, "failed to fetch letters") return } response.JSON(w, http.StatusOK, docs) } func (h *LetterHandler) GetByRecipient(w http.ResponseWriter, r *http.Request) { name := chi.URLParam(r, "name") docs, err := h.repo.GetByRecipient(r.Context(), name) if err != nil { response.Error(w, http.StatusInternalServerError, "failed to fetch letters") return } response.JSON(w, http.StatusOK, docs) } func (h *LetterHandler) GetByLocation(w http.ResponseWriter, r *http.Request) { name := chi.URLParam(r, "name") docs, err := h.repo.GetByLocation(r.Context(), name) if err != nil { response.Error(w, http.StatusInternalServerError, "failed to fetch letters") return } response.JSON(w, http.StatusOK, docs) } func (h *LetterHandler) GetYears(w http.ResponseWriter, r *http.Request) { docs, err := h.repo.GetYears(r.Context()) if err != nil { response.Error(w, http.StatusInternalServerError, "failed to fetch years") return } response.JSON(w, http.StatusOK, docs) } func (h *LetterHandler) GetRecipients(w http.ResponseWriter, r *http.Request) { docs, err := h.repo.GetRecipients(r.Context()) if err != nil { response.Error(w, http.StatusInternalServerError, "failed to fetch recipients") return } response.JSON(w, http.StatusOK, docs) } func (h *LetterHandler) GetLocations(w http.ResponseWriter, r *http.Request) { docs, err := h.repo.GetLocations(r.Context()) if err != nil { response.Error(w, http.StatusInternalServerError, "failed to fetch locations") return } response.JSON(w, http.StatusOK, docs) } func (h *LetterHandler) Count(w http.ResponseWriter, r *http.Request) { count, err := h.repo.Count(r.Context()) if err != nil { response.Error(w, http.StatusInternalServerError, "failed to count letters") return } response.JSON(w, http.StatusOK, map[string]int64{"count": count}) }