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

module Jobs.Handler.Invitation
  ( dispatchJobInvitation
  ) where

import Import
import Handler.Utils.Mail

import qualified Data.CaseInsensitive as CI
import Text.Hamlet


dispatchJobInvitation :: Maybe UserId
                      -> UserEmail
                      -> Text
                      -> Text
                      -> Html
                      -> JobHandler UniWorX
dispatchJobInvitation jInviter jInvitee jInvitationUrl jInvitationSubject jInvitationExplanation = JobHandlerException $ do
  mInviter <- join <$> traverse (runDB . get) jInviter

  mailT def $ do
    _mailTo .= [Address Nothing $ CI.original jInvitee]
    whenIsJust mInviter $ \jInviter' ->
      replaceMailHeader "Reply-To" . Just . renderAddress $ userAddressFrom jInviter'
    replaceMailHeader "Auto-Submitted" $ Just "auto-generated"
    replaceMailHeader "Subject" $ Just jInvitationSubject
    addHtmlMarkdownAlternatives ($(ihamletFile "templates/mail/invitation.hamlet") :: HtmlUrlI18n (SomeMessage UniWorX) (Route UniWorX))
