;; simple-shortener.fnl
;; Top-level server logic

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

(local lume (require :lume))
(local turbo (require :turbo))

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

(local auth_utils (require :modules.auth_utils))
(local config (require :modules.config))

;; -------------------------------------------------------------------------- ;;
;; Request handlers

(local LinksAPIHandler (require :handlers.LinksAPIHandler))
(local RedirectHandler (require :handlers.RedirectHandler))
(local SessionAPIHandler (require :handlers.SessionAPIHandler))
(local ValidateAPIHandler (require :handlers.ValidateAPIHandler))

;; -------------------------------------------------------------------------- ;;
;; Assemble route list

(local route_list (lume.concat

                     ;; Static control panel app (if enabled)
                     (when config.enable_control_panel
                       [["^/shorten/?$" turbo.web.StaticFileHandler "static/control_panel/index.html"]
                        ["^/shorten/static/(.*)$" turbo.web.StaticFileHandler "static/control_panel/"]])

                     ;; API endpoints
                     [["^/shorten/api/links/?$" LinksAPIHandler]
                      ["^/shorten/api/links/([%a%d]+)$" LinksAPIHandler]
                      ["^/shorten/api/session/?$" SessionAPIHandler]
                      ["^/shorten/api/session/([%a%d]+)$" SessionAPIHandler]
                      ["^/shorten/api/validate/([%a_]+)$" ValidateAPIHandler]]

                     ;; Redirect handler
                     [["^/([%a%d]+)$" RedirectHandler]]

                     ;; Static landing page (if enabled)
                     (when config.enable_landing_page
                       [["^/$" turbo.web.StaticFileHandler (.. "static/landing_page/" config.landing_page_index)]
                        ["^/(.*)$" turbo.web.StaticFileHandler "static/landing_page/"]])))

;; -------------------------------------------------------------------------- ;;
;; Server initialization

;; ---------------------------------- ;;
;; Print TOTP QR (if TOTP auth is enabled)

(when config.use_totp
  (auth_utils.print_totp_qr))

;; ---------------------------------- ;;
;; Print any applicable warnings

(when (= _G.TURBO_STATIC_MAX -1)
  (print "🚧 WARNING: Static file caching is disabled!"))

(when (not config.use_secure_cookies)
  (print "🚧 WARNING: Secure cookies are disabled!"))

;; ---------------------------------- ;;
;; Start server

(let [app (turbo.web.Application:new route_list)
      ioloop (turbo.ioloop.instance)]
  (app:listen config.listen_port)
  (print (.. "✅ Listening on port " (tostring config.listen_port) "."))
  (ioloop:start))
