-- SPDX-FileCopyrightText: 2022 Gregor Kleen <gregor.kleen@ifi.lmu.de>,Sarah Vaupel <vaupel.sarah@campus.lmu.de>
--
-- SPDX-License-Identifier: AGPL-3.0-or-later

module Jobs.Handler.HelpRequest
  ( dispatchJobHelpRequest
  ) where

import Import

import Text.Hamlet
import qualified Data.CaseInsensitive as CI

import Handler.Utils

import Data.Bitraversable


dispatchJobHelpRequest :: Either (Maybe Address) UserId
                       -> UTCTime
                       -> Maybe Text -- ^ Help Subject
                       -> Maybe Html -- ^ Help Request
                       -> Maybe Text -- ^ Referer
                       -> Maybe ErrorResponse
                       -> JobHandler UniWorX
dispatchJobHelpRequest jSender jRequestTime jHelpSubject jHelpRequest jReferer jError = JobHandlerException $ do
  supportAddress <- getsYesod $ view _appMailSupport
  userInfo <- bitraverse return (runDB . getEntity) jSender
  let senderAddress = either
        id
        (fmap $ \(Entity _ User{..}) -> Address (Just userDisplayName) (CI.original userEmail))
        userInfo
  mailT def $ do
    _mailTo .= [supportAddress]
    whenIsJust senderAddress (_mailFrom .=)
    replaceMailHeader "Auto-Submitted" $ Just "no"
    setSubjectI $ maybe MsgMailSubjectSupport MsgMailSubjectSupportCustom jHelpSubject
    setDate jRequestTime
    rtime <- formatTimeMail SelFormatDateTime jRequestTime

    addHtmlMarkdownAlternatives ($(ihamletFile "templates/mail/support.hamlet") :: HtmlUrlI18n UniWorXMessage (Route UniWorX))
