-- SPDX-FileCopyrightText: 2022 Gregor Kleen <gregor.kleen@ifi.lmu.de>
--
-- SPDX-License-Identifier: AGPL-3.0-or-later

{-# OPTIONS_GHC -fno-warn-unused-do-bind #-} -- ihamletFile discards do results

module Jobs.Handler.SendNotification.SubmissionRated
  ( dispatchNotificationSubmissionRated
  ) where

import Import

import Handler.Utils
import Jobs.Handler.SendNotification.Utils

import Text.Hamlet
import qualified Data.CaseInsensitive as CI


dispatchNotificationSubmissionRated :: SubmissionId -> UserId -> Handler ()
dispatchNotificationSubmissionRated nSubmission jRecipient = maybeT_ $ do
  (Course{..}, Sheet{..}, Submission{..}, corrector, sheetTypeDesc, hasAccess, csid) <- lift . runDB $ do
    submission@Submission{submissionRatingBy} <- getJust nSubmission
    sheet@Sheet{sheetName} <- belongsToJust submissionSheet submission
    course@Course{..} <- belongsToJust sheetCourse sheet
    corrector <- traverse getJust submissionRatingBy
    sheetTypeDesc <- sheetTypeDescription (sheetCourse sheet) (sheetType sheet)
    csid <- encrypt nSubmission

    hasAccess <- is _Authorized <$> evalAccessForDB (Just jRecipient) (CSubmissionR courseTerm courseSchool courseShorthand sheetName csid CorrectionR) False
    return (course, sheet, submission, corrector, sheetTypeDesc, hasAccess, csid)

  guard hasAccess

  lift . userMailT jRecipient $ do
    whenIsJust corrector $ \corrector' ->
      addMailHeader "Reply-To" . renderAddress $ userAddressFrom corrector'
    replaceMailHeader "Auto-Submitted" $ Just "auto-generated"
    setSubjectI $ MsgMailSubjectSubmissionRated courseShorthand

    MsgRenderer mr <- getMailMsgRenderer
    let termDesc = mr . ShortTermIdentifier $ unTermKey courseTerm
    submissionRatingTime' <- traverse (formatTimeMail SelFormatDateTime) submissionRatingTime
    let tid = courseTerm
        ssh = courseSchool
        csh = courseShorthand
        shn = sheetName

    editNotifications <- mkEditNotifications jRecipient

    addHtmlMarkdownAlternatives ($(ihamletFile "templates/mail/submissionRated.hamlet") :: HtmlUrlI18n (SomeMessage UniWorX) (Route UniWorX))
