package inventory import ( "context" "fmt" "net/http" ) // StockReader abstracts the inventory getter for badge rendering. type StockReader interface { GetInventory(ctx context.Context, sku SKU, locationID LocationID) (int64, error) } // BadgeHandler returns an http.HandlerFunc that renders an HTML stock badge fragment. func BadgeHandler(reader StockReader) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { sku := r.URL.Query().Get("sku") if sku == "" { http.Error(w, "missing sku parameter", http.StatusBadRequest) return } locationID := LocationID(r.URL.Query().Get("location_id")) if locationID == "" { locationID = LocationID(r.URL.Query().Get("country")) } if locationID == "" { locationID = "se" } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Cache-Control", "private, max-age=5") qty, err := reader.GetInventory(r.Context(), SKU(sku), locationID) if err != nil { w.WriteHeader(http.StatusOK) w.Write([]byte(`Availability unavailable`)) return } var htmlSnippet string switch { case qty > 10: htmlSnippet = fmt.Sprintf(`✓ In stock`, sku) case qty > 0: htmlSnippet = fmt.Sprintf(`⚡ Only %d left!`, sku, qty) default: htmlSnippet = fmt.Sprintf(`✕ Out of stock`, sku) } w.WriteHeader(http.StatusOK) w.Write([]byte(htmlSnippet)) } }