package checkin import ( "encoding/json" "errors" "net/http" "git.unsupervised.ca/walkies/internal/respond" "git.unsupervised.ca/walkies/internal/server/middleware" ) type Handler struct { store *Store } func NewHandler(store *Store) *Handler { return &Handler{store: store} } // POST /api/v1/checkin func (h *Handler) CheckIn(w http.ResponseWriter, r *http.Request) { claims := middleware.ClaimsFromContext(r.Context()) var in CheckInInput if err := json.NewDecoder(r.Body).Decode(&in); err != nil { respond.Error(w, http.StatusBadRequest, "invalid request body") return } ci, err := h.store.CheckIn(r.Context(), claims.VolunteerID, in) if errors.Is(err, ErrAlreadyCheckedIn) { respond.Error(w, http.StatusConflict, err.Error()) return } if err != nil { respond.Error(w, http.StatusInternalServerError, "could not check in") return } respond.JSON(w, http.StatusCreated, ci) } // POST /api/v1/checkout func (h *Handler) CheckOut(w http.ResponseWriter, r *http.Request) { claims := middleware.ClaimsFromContext(r.Context()) var in CheckOutInput json.NewDecoder(r.Body).Decode(&in) ci, err := h.store.CheckOut(r.Context(), claims.VolunteerID, in) if errors.Is(err, ErrNotCheckedIn) { respond.Error(w, http.StatusConflict, err.Error()) return } if err != nil { respond.Error(w, http.StatusInternalServerError, "could not check out") return } respond.JSON(w, http.StatusOK, ci) } // GET /api/v1/checkin/history func (h *Handler) History(w http.ResponseWriter, r *http.Request) { claims := middleware.ClaimsFromContext(r.Context()) volunteerID := int64(0) if claims.Role != "admin" { volunteerID = claims.VolunteerID } history, err := h.store.History(r.Context(), volunteerID) if err != nil { respond.Error(w, http.StatusInternalServerError, "could not get history") return } if history == nil { history = []CheckIn{} } respond.JSON(w, http.StatusOK, history) }