;; Market link-card fragment handler
;; returns: sx
;;
;; Renders product preview card(s) by slug.
;; Supports single mode (?slug=x) and batch mode (?keys=x,y,z).

(defhandler link-card (&key slug keys)
  (if keys
    (let ((slugs (filter (fn (s) (not (empty? s)))
                   (map trim (split keys ",")))))
      (<> (map (fn (s)
        (let ((product (service "market" "product-by-slug" :slug s)))
          (<> (str "<!-- fragment:" s " -->")
              (when (not (nil? product))
                (let ((link (app-url "market" (str "/product/" (get product "slug") "/")))
                      (subtitle (or (get product "brand") ""))
                      (detail (if (get product "special_price")
                                (str (get product "regular_price") " → " (get product "special_price"))
                                (if (get product "regular_price")
                                  (str (get product "regular_price"))
                                  ""))))
                  (~link-card
                    :title (get product "title")
                    :image (get product "image")
                    :subtitle subtitle
                    :detail detail
                    :link link)))))) slugs)))
    (when slug
      (let ((product (service "market" "product-by-slug" :slug slug)))
        (when (not (nil? product))
          (let ((link (app-url "market" (str "/product/" (get product "slug") "/")))
                (subtitle (or (get product "brand") ""))
                (detail (if (get product "special_price")
                          (str (get product "regular_price") " → " (get product "special_price"))
                          (if (get product "regular_price")
                            (str (get product "regular_price"))
                            ""))))
            (~link-card
              :title (get product "title")
              :image (get product "image")
              :subtitle subtitle
              :detail detail
              :link link)))))))
