module Jobs.Handler.ChangeUserDisplayEmail
  ( dispatchJobChangeUserDisplayEmail
  ) where

import Import

import Handler.Utils.Mail
import qualified Data.HashSet as HashSet
import qualified Data.CaseInsensitive as CI

import Text.Hamlet

dispatchJobChangeUserDisplayEmail :: UserId -> UserEmail -> Handler ()
dispatchJobChangeUserDisplayEmail jUser jDisplayEmail = do
  token <- tokenRestrict SetDisplayEmailR jDisplayEmail <$> bearerToken (Right jUser) (Just $ HashSet.singleton SetDisplayEmailR) Nothing Nothing Nothing
  jwt <- encodeToken token
  let
    setDisplayEmailUrl :: SomeRoute UniWorX
    setDisplayEmailUrl = SomeRoute (SetDisplayEmailR, [(toPathPiece GetBearer, toPathPiece jwt)])
  setDisplayEmailUrl' <- toTextUrl setDisplayEmailUrl

  user@User{..} <- runDB $ getJust jUser

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