module Jobs.Handler.CorrectorInvitation
  ( dispatchJobCorrectorInvitation
  ) where

import Import

import Text.Hamlet

import qualified Data.HashSet as HashSet

import qualified Data.CaseInsensitive as CI

import Utils.Lens


dispatchJobCorrectorInvitation :: UserId -> SheetCorrectorInvitation -> Handler ()
dispatchJobCorrectorInvitation jInviter jCorrectorInvitation@SheetCorrectorInvitation{..} = do
  ctx <- runDB . runMaybeT $ do
    sheet <- MaybeT $ get sheetCorrectorInvitationSheet
    course <- MaybeT . get $ sheetCourse sheet
    void . MaybeT $ getByValue jCorrectorInvitation
    user <- MaybeT $ get jInviter
    return (sheet, course, user)

  case ctx of
    Just (Sheet{..}, Course{..}, User{..}) -> do
      let baseRoute = CSheetR courseTerm courseSchool courseShorthand sheetName $ SCorrInviteR sheetCorrectorInvitationEmail
      jwt <- encodeToken =<< bearerToken jInviter (Just $ HashSet.singleton baseRoute) Nothing Nothing Nothing
      let
        invitationUrl :: SomeRoute UniWorX
        invitationUrl = SomeRoute (baseRoute, [(toPathPiece GetBearer, toPathPiece jwt)])
      invitationUrl' <- toTextUrl invitationUrl

      mailT def $ do
        _mailTo .= [Address Nothing $ CI.original sheetCorrectorInvitationEmail]
        replaceMailHeader "Reply-To" . Just . renderAddress $ Address (Just userDisplayName) (CI.original userEmail)
        replaceMailHeader "Auto-Submitted" $ Just "auto-generated"
        setSubjectI $ MsgMailSubjectCorrectorInvitation courseTerm courseSchool courseShorthand sheetName
      
        addPart ($(ihamletFile "templates/mail/correctorInvitation.hamlet") :: HtmlUrlI18n UniWorXMessage (Route UniWorX))
    Nothing -> runDB .
      deleteBy $ UniqueSheetCorrectorInvitation sheetCorrectorInvitationEmail sheetCorrectorInvitationSheet
