;; handlers/RedirectHandler.fnl
;; Provides a RequestHandler that handles redirects for shortened links

;; -------------------------------------------------------------------------- ;;
;; Dependencies

(local turbo (require :turbo))

;; -------------------------------------------------------------------------- ;;
;; Local modules

(local links_db (require :modules.links_db))

;; -------------------------------------------------------------------------- ;;
;; Handler definition

(local RedirectHandler (class "RedirectHandler" turbo.web.RequestHandler))

;; ---------------------------------- ;;
;; GET

(fn RedirectHandler.get [self link_id]
  "Redirect the client to the destination of the link with ID `link_id` in the database.
If `link_id` is found, the link will also have its visit count incremented by one.
If `link_id` is not found, the client will be redirected to root.
Responds with 302 Found and a redirect header."
  (let [dest (links_db.fetch_link_dest link_id)]
    (when dest (links_db.increment_link_visit_count link_id))
    (self:redirect (or dest "/"))))

;; -------------------------------------------------------------------------- ;;
;; Return handler

RedirectHandler
