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

module Handler.Tutorial.Register
  ( postTRegisterR
  ) where

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


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
      ok <- runDB $ do
        fsh <- selectCompanyUserPrime' uid
        insertUnique $ TutorialParticipant tutid uid fsh Nothing Nothing Nothing
      if isJust ok
        then addMessageI Success $ MsgTutorialRegisteredSuccess tutorialName
        else addMessageI Error   $ MsgTutorialRegisteredFail    tutorialName   -- cannot happen, but it is nonetheless better to be safe than crashing
      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"]
