module Jobs.Handler.SendCourseCommunication
  ( dispatchJobSendCourseCommunication
  ) where

import Import

import Utils.Lens
import Handler.Utils

import qualified Data.Set as Set

import qualified Data.CaseInsensitive as CI


dispatchJobSendCourseCommunication :: Either UserEmail UserId
                                   -> Set Address
                                   -> CourseId
                                   -> UserId
                                   -> UUID
                                   -> Maybe Text
                                   -> Html
                                   -> Handler ()
dispatchJobSendCourseCommunication jRecipientEmail jAllRecipientAddresses jCourse jSender jMailObjectUUID jSubject jMailContent = do
  (sender, Course{..}) <- runDB $ (,)
    <$> getJust jSender
    <*> getJust jCourse
  either (\email -> mailT def . (assign _mailTo (pure . Address Nothing $ CI.original email) *>)) userMailT jRecipientEmail $ do
    void $ setMailObjectUUID jMailObjectUUID
    _mailFrom .= userAddress sender
    if -- Use `addMailHeader` instead of `_mailCc` to make `mailT` ignore the additional recipients
      | jRecipientEmail == Right jSender
      -> addMailHeader "Cc" . intercalate ", " . map renderAddress $ Set.toAscList (Set.delete (userAddress sender) jAllRecipientAddresses)
      | otherwise
      -> addMailHeader "Cc" "Undisclosed Recipients:;"
    addMailHeader "Auto-Submitted" "no"
    setSubjectI . prependCourseTitle courseTerm courseSchool courseShorthand $ maybe (SomeMessage MsgCommCourseSubject) SomeMessage jSubject
    void $ addPart jMailContent
