module Handler.Tutorial.Register
  ( postTRegisterR
  ) where

import Import
import Handler.Utils
import Handler.Utils.Tutorial


postTRegisterR :: TermId -> SchoolId -> CourseShorthand -> TutorialName -> Handler ()
postTRegisterR tid ssh csh tutn = do
  uid <- requireAuthId

  Entity tutid Tutorial{..} <- runDB $ fetchTutorial tid ssh csh tutn

  ((btnResult, _), _) <- runFormPost buttonForm

  formResult btnResult $ \case
    BtnRegister -> do
      runDB . void . insert $ TutorialParticipant tutid uid
      addMessageI Success $ MsgTutorialRegisteredSuccess tutorialName
      redirect $ CourseR tid ssh csh CShowR
    BtnDeregister -> do
      runDB . deleteBy $ UniqueTutorialParticipant tutid uid
      addMessageI Success $ MsgTutorialDeregisteredSuccess tutorialName
      redirect $ CourseR tid ssh csh CShowR

  invalidArgs ["Register/Deregister button required"]
