package handler import ( "encoding/json" "errors" "net/http" "strconv" "github.com/go-chi/chi/v5" "financeiro-carvalho/internal/model" "financeiro-carvalho/internal/service" ) type AccountHandler struct { svc *service.AccountService } func NewAccountHandler(svc *service.AccountService) *AccountHandler { return &AccountHandler{svc: svc} } func (h *AccountHandler) List(w http.ResponseWriter, r *http.Request) { items, err := h.svc.List(r.Context()) if err != nil { respondError(w, http.StatusInternalServerError, "failed to list accounts") return } if items == nil { items = []model.Account{} } respondJSON(w, http.StatusOK, items) } func (h *AccountHandler) Create(w http.ResponseWriter, r *http.Request) { var in model.AccountInput if err := json.NewDecoder(r.Body).Decode(&in); err != nil { respondError(w, http.StatusBadRequest, "invalid JSON") return } out, err := h.svc.Create(r.Context(), in) if err != nil { if errors.Is(err, service.ErrAccountEmptyName) || errors.Is(err, service.ErrAccountInvalidType) { respondError(w, http.StatusUnprocessableEntity, err.Error()) return } respondError(w, http.StatusInternalServerError, "failed to create account") return } respondJSON(w, http.StatusCreated, out) } func (h *AccountHandler) Update(w http.ResponseWriter, r *http.Request) { id, err := strconv.Atoi(chi.URLParam(r, "id")) if err != nil { respondError(w, http.StatusBadRequest, "invalid id") return } var in model.AccountInput if err := json.NewDecoder(r.Body).Decode(&in); err != nil { respondError(w, http.StatusBadRequest, "invalid JSON") return } out, err := h.svc.Update(r.Context(), id, in) if err != nil { if errors.Is(err, service.ErrAccountEmptyName) || errors.Is(err, service.ErrAccountInvalidType) { respondError(w, http.StatusUnprocessableEntity, err.Error()) return } respondError(w, http.StatusInternalServerError, "failed to update account") return } respondJSON(w, http.StatusOK, out) } func (h *AccountHandler) Delete(w http.ResponseWriter, r *http.Request) { id, err := strconv.Atoi(chi.URLParam(r, "id")) if err != nil { respondError(w, http.StatusBadRequest, "invalid id") return } if err := h.svc.Delete(r.Context(), id); err != nil { respondError(w, http.StatusInternalServerError, "failed to delete account") return } w.WriteHeader(http.StatusNoContent) }