package handlers import ( "database/sql" "encoding/json" "errors" "fmt" "net/http" "time" "github.com/google/uuid" "github.com/jmoiron/sqlx" "vlog/internal/auth" "vlog/internal/models" "vlog/internal/storage" ) // ServiceEntryWithFiles is the shape returned to the frontend: an entry plus // its attachments, so the timeline can render everything in one fetch. type ServiceEntryWithFiles struct { models.ServiceEntry Files []models.ServiceEntryFile `json:"files"` } // ListServiceEntries returns one page of a car's service history, newest // first — the "timeline" is just this list rendered chronologically, // nothing fancier. Paginated (?limit=&offset=) so a long history doesn't // mean dumping thousands of rows into a single response/DOM. func (h *Handlers) ListServiceEntries(w http.ResponseWriter, r *http.Request) { car, ok := h.loadOwnedCar(w, r) if !ok { return } limit, offset := parsePagination(r) var entries []models.ServiceEntry err := h.dbSelect(r.Context(), &entries, ` SELECT * FROM service_entries WHERE car_id = ? ORDER BY entry_date DESC, created_at DESC LIMIT ? OFFSET ? `, car.ID, limit+1, offset) if err != nil { writeError(w, http.StatusInternalServerError, "failed to list service entries") return } entries, hasMore := paginate(limit, entries) writeJSON(w, http.StatusOK, page[ServiceEntryWithFiles]{ Items: h.attachFiles(r, entries), HasMore: hasMore, }) } // attachFiles batches a single query for all files belonging to entries, // rather than one query per entry. func (h *Handlers) attachFiles(r *http.Request, entries []models.ServiceEntry) []ServiceEntryWithFiles { result := make([]ServiceEntryWithFiles, len(entries)) ids := make([]string, len(entries)) for i, e := range entries { result[i] = ServiceEntryWithFiles{ServiceEntry: e, Files: []models.ServiceEntryFile{}} ids[i] = e.ID } if len(ids) == 0 { return result } // sqlx.In expands the slice into the right number of "?" placeholders; // Rebind then adapts those for whichever driver is actually connected. query, args, err := sqlx.In(`SELECT * FROM service_entry_files WHERE service_entry_id IN (?) ORDER BY created_at`, ids) if err != nil { return result // best-effort: entries without file metadata beats a 500 } var files []models.ServiceEntryFile if err := h.dbSelect(r.Context(), &files, query, args...); err != nil { return result } byEntry := make(map[string][]models.ServiceEntryFile, len(ids)) for _, f := range files { byEntry[f.ServiceEntryID] = append(byEntry[f.ServiceEntryID], f) } for i := range result { if fs, ok := byEntry[result[i].ID]; ok { result[i].Files = fs } } return result } // CreateServiceEntry adds a new history entry to a car. func (h *Handlers) CreateServiceEntry(w http.ResponseWriter, r *http.Request) { car, ok := h.loadOwnedCar(w, r) if !ok { return } var in models.ServiceEntryInput if err := json.NewDecoder(r.Body).Decode(&in); err != nil { writeError(w, http.StatusBadRequest, "invalid request body") return } if in.EntryType == "" { writeError(w, http.StatusBadRequest, "entryType is required") return } entryDate, err := time.Parse(dateLayout, in.EntryDate) if err != nil { writeError(w, http.StatusBadRequest, "invalid entryDate") return } var entry models.ServiceEntry err = h.dbGet(r.Context(), &entry, ` INSERT INTO service_entries (id, car_id, entry_date, entry_type, description, performed_at, odometer, is_service) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING * `, uuid.New().String(), car.ID, entryDate, in.EntryType, in.Description, in.PerformedAt, in.Odometer, in.IsService) if err != nil { writeError(w, http.StatusInternalServerError, "failed to create service entry") return } writeJSON(w, http.StatusCreated, ServiceEntryWithFiles{ServiceEntry: entry, Files: []models.ServiceEntryFile{}}) } // GetServiceEntry returns one entry with its attachments. func (h *Handlers) GetServiceEntry(w http.ResponseWriter, r *http.Request) { entry, ok := h.loadOwnedServiceEntry(w, r) if !ok { return } result := h.attachFiles(r, []models.ServiceEntry{*entry}) writeJSON(w, http.StatusOK, result[0]) } // UpdateServiceEntry edits an entry's fields. func (h *Handlers) UpdateServiceEntry(w http.ResponseWriter, r *http.Request) { entry, ok := h.loadOwnedServiceEntry(w, r) if !ok { return } var in models.ServiceEntryInput if err := json.NewDecoder(r.Body).Decode(&in); err != nil { writeError(w, http.StatusBadRequest, "invalid request body") return } if in.EntryType == "" { writeError(w, http.StatusBadRequest, "entryType is required") return } entryDate, err := time.Parse(dateLayout, in.EntryDate) if err != nil { writeError(w, http.StatusBadRequest, "invalid entryDate") return } var updated models.ServiceEntry err = h.dbGet(r.Context(), &updated, ` UPDATE service_entries SET entry_date = ?, entry_type = ?, description = ?, performed_at = ?, odometer = ?, is_service = ? WHERE id = ? RETURNING * `, entryDate, in.EntryType, in.Description, in.PerformedAt, in.Odometer, in.IsService, entry.ID) if err != nil { writeError(w, http.StatusInternalServerError, "failed to update service entry") return } result := h.attachFiles(r, []models.ServiceEntry{updated}) writeJSON(w, http.StatusOK, result[0]) } // DeleteServiceEntry removes an entry (DB cascades to its files; storage // cleanup of each attached file is best-effort). func (h *Handlers) DeleteServiceEntry(w http.ResponseWriter, r *http.Request) { entry, ok := h.loadOwnedServiceEntry(w, r) if !ok { return } var files []models.ServiceEntryFile _ = h.dbSelect(r.Context(), &files, `SELECT * FROM service_entry_files WHERE service_entry_id = ?`, entry.ID) if _, err := h.dbExec(r.Context(), `DELETE FROM service_entries WHERE id = ?`, entry.ID); err != nil { writeError(w, http.StatusInternalServerError, "failed to delete service entry") return } for _, f := range files { _ = h.Storage.Delete(r.Context(), f.S3Key) } writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) } // UploadServiceEntryFile attaches one PNG/PDF file to an entry. Call once // per file for multi-file uploads. func (h *Handlers) UploadServiceEntryFile(w http.ResponseWriter, r *http.Request) { entry, ok := h.loadOwnedServiceEntry(w, r) if !ok { return } file, contentType, ok := parseUploadedFile(w, r, 15<<20, storage.AllowedAttachmentTypes) if !ok { return } defer file.Close() _, header, _ := r.FormFile("file") originalName := "attachment" if header != nil { originalName = sanitizeFileName(header.Filename) } userID, _ := auth.UserIDFromContext(r.Context()) key := fmt.Sprintf("users/%s/cars/%s/service/%s/%s-%s", userID, entry.CarID, entry.ID, randomID(), originalName) var sizeBytes int64 if header != nil { sizeBytes = header.Size } if err := h.Storage.Upload(r.Context(), key, contentType, file); err != nil { writeError(w, http.StatusInternalServerError, "failed to upload file") return } var saved models.ServiceEntryFile err := h.dbGet(r.Context(), &saved, ` INSERT INTO service_entry_files (id, service_entry_id, s3_key, file_name, content_type, size_bytes) VALUES (?, ?, ?, ?, ?, ?) RETURNING * `, uuid.New().String(), entry.ID, key, originalName, contentType, sizeBytes) if err != nil { writeError(w, http.StatusInternalServerError, "failed to save file reference") return } writeJSON(w, http.StatusCreated, saved) } func (h *Handlers) loadOwnedServiceEntry(w http.ResponseWriter, r *http.Request) (*models.ServiceEntry, bool) { userID, _ := auth.UserIDFromContext(r.Context()) entryID := r.PathValue("entryId") var entry models.ServiceEntry err := h.dbGet(r.Context(), &entry, ` SELECT se.* FROM service_entries se JOIN cars c ON c.id = se.car_id WHERE se.id = ? AND c.user_id = ? `, entryID, userID) if errors.Is(err, sql.ErrNoRows) { writeError(w, http.StatusNotFound, "service entry not found") return nil, false } if err != nil { writeError(w, http.StatusInternalServerError, "failed to load service entry") return nil, false } return &entry, true }