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

module Jobs.Handler.ChangeUserDisplayEmail
  ( dispatchJobChangeUserDisplayEmail
  ) where

import Import

import Handler.Utils.Mail
import Handler.Utils.Users
import qualified Data.HashSet as HashSet
import qualified Data.HashMap.Strict as HashMap
import qualified Data.CaseInsensitive as CI

import Text.Hamlet

dispatchJobChangeUserDisplayEmail :: UserId -> UserEmail -> JobHandler UniWorX
dispatchJobChangeUserDisplayEmail jUser jDisplayEmail = JobHandlerException $ do
  bearer <- bearerRestrict SetDisplayEmailR jDisplayEmail <$> bearerToken (HashSet.singleton $ Right jUser) Nothing (HashMap.singleton BearerTokenRouteEval $ HashSet.singleton SetDisplayEmailR) Nothing Nothing Nothing
  jwt <- encodeBearer bearer
  let
    setDisplayEmailUrl :: SomeRoute UniWorX
    setDisplayEmailUrl = SomeRoute (SetDisplayEmailR, [(toPathPiece GetBearer, toPathPiece jwt)])
  setDisplayEmailUrl' <- toTextUrl setDisplayEmailUrl

  (Entity{entityVal=User{..}}, userAddress) <- runDB $ do
    usrEnt <- getJustEntity jUser -- error aborts job
    usrAdr <- getJustEmailAddress usrEnt
    return (usrEnt, usrAdr)

  userMailT jUser $ do
    _mailTo .= pure (userAddress & _addressEmail .~ CI.original jDisplayEmail)
    replaceMailHeader "Auto-Submitted" $ Just "auto-generated"
    setSubjectI MsgMailSubjectChangeUserDisplayEmail
    addHtmlMarkdownAlternatives ($(ihamletFile "templates/mail/changeUserDisplayEmail.hamlet") :: HtmlUrlI18n (SomeMessage UniWorX) (Route UniWorX))
