package store import ( "fmt" "path/filepath" "time" "github.com/google/uuid" "printer.backend/internal/model" "printer.backend/internal/paths" ) // PlateStore persists plates as JSON files. type PlateStore struct { dir string } // NewPlateStore creates a store under dir (default data/plates). func NewPlateStore(dir string) *PlateStore { if dir == "" { dir = paths.PlatesDir } return &PlateStore{dir: dir} } // List returns all plates sorted by creation time (newest first). func (s *PlateStore) List() ([]model.Plate, error) { return listFromDir(s.dir, func(name string) bool { return filepath.Ext(name) == ".json" }, "plates dir", func(p model.Plate) time.Time { return p.CreatedAt }, ) } // Save writes a new plate and assigns an ID when empty. func (s *PlateStore) Save(p model.Plate) (model.Plate, error) { if err := ensureDir(s.dir); err != nil { return model.Plate{}, err } if p.ID == "" { p.ID = uuid.NewString() } p.CreatedAt = stampNew(&p.CreatedAt) path := filepath.Join(s.dir, p.ID+".json") if err := writeJSON(path, p); err != nil { return model.Plate{}, fmt.Errorf("write plate: %w", err) } return p, nil } // Update replaces an existing plate by ID (preserves created_at). func (s *PlateStore) Update(id string, p model.Plate) (model.Plate, error) { path := filepath.Join(s.dir, id+".json") existing, err := readJSON[model.Plate](path) if err != nil { return model.Plate{}, fmt.Errorf("plate not found: %s", id) } p.ID = existing.ID p.CreatedAt = existing.CreatedAt if err := writeJSON(path, p); err != nil { return model.Plate{}, fmt.Errorf("write plate: %w", err) } return p, nil } // Delete removes a plate by ID. func (s *PlateStore) Delete(id string) error { path := filepath.Join(s.dir, id+".json") return removeFile(path, fmt.Sprintf("plate not found: %s", id)) }