module Jobs.Handler.PruneOldSentMails
  ( dispatchJobPruneOldSentMails
  ) where

import Import

import qualified Database.Esqueleto.Legacy as E
import Database.Persist.Sql (deleteWhereCount)


dispatchJobPruneOldSentMails :: JobHandler UniWorX
dispatchJobPruneOldSentMails = JobHandlerAtomic $ do
  retain' <- getsYesod $ view _appMailRetainSent
  whenIsJust retain' $ \retain -> do
    now <- liftIO getCurrentTime
    del <- deleteWhereCount [SentMailSentAt <. addUTCTime (-retain) now]
    $logInfoS "JobPruneOldSentMails" [st|Deleted #{del} old sent mails|]
  del <- E.deleteCount . E.from $ \sentMailContent ->
    E.where_ . E.not_ . E.exists . E.from $ \sentMail ->
      E.where_ $ sentMail E.^. SentMailContentRef E.==. sentMailContent E.^. SentMailContentId
  $logInfoS "JobPruneOldSentMails" [st|Deleted #{del} old sent mail bodies|]
