module Utils.Tutorial
  ( isTutorialTutor, isTutorialParticipant
  ) where

import Import

import qualified Database.Esqueleto as E
import qualified Database.Esqueleto.Utils as E


isTutorialTutor :: Maybe UserId -> AuthTagActive -> E.SqlExpr (E.Value TutorialId) -> E.SqlExpr (E.Value Bool)
isTutorialTutor muid AuthTagActive{..} tid
  | Just uid <- muid, authTagIsActive AuthTutor = E.exists . E.from $ \(tutor `E.InnerJoin` tutorial) -> do
    E.on $     tutor    E.^. TutorTutorial E.==. tutorial E.^. TutorialId
    E.where_ $ tutorial E.^. TutorialId    E.==. tid
      E.&&.    tutor    E.^. TutorUser     E.==. E.val uid
  | otherwise = E.false

isTutorialParticipant :: Maybe UserId -> AuthTagActive -> E.SqlExpr (E.Value TutorialId) -> E.SqlExpr (E.Value Bool)
isTutorialParticipant muid AuthTagActive{..} tid
  | Just uid <- muid, authTagIsActive AuthTutorialRegistered = E.exists . E.from $ \(tutorialParticipant `E.InnerJoin` tutorial) -> do
    E.on $     tutorialParticipant E.^. TutorialParticipantTutorial E.==. tutorial E.^. TutorialId
    E.where_ $ tutorial            E.^. TutorialId                  E.==. tid
      E.&&.    tutorialParticipant E.^. TutorialParticipantUser     E.==. E.val uid
  | otherwise = E.false
