module Jobs.Handler.ChangeUserDisplayEmail
  ( dispatchJobChangeUserDisplayEmail
  ) where

import Import

import Handler.Utils.Mail
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

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

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