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

module Handler.Course.Delete
  ( getCDeleteR, postCDeleteR
  ) where

import Import

import Handler.Utils.Course
import Handler.Utils.Delete

import qualified Data.Set as Set


getCDeleteR, postCDeleteR :: TermId -> SchoolId -> CourseShorthand -> Handler Html
getCDeleteR = postCDeleteR
postCDeleteR tid ssh csh = do
  (cId, activeParticipants, existExams) <- runDB $ do
    Entity cId _ <- getBy404 $ TermSchoolCourseShort tid ssh csh
    activeParticipants <- exists [CourseParticipantState ==. CourseParticipantActive, CourseParticipantCourse ==. cId]
    existExams <- exists [ExamCourse ==. cId]
    return (cId, activeParticipants, existExams)
  if 
    | activeParticipants -> do
      addMessageI Error MsgCourseDeleteActiveParticipants
      redirect $ CourseR tid ssh csh CUsersR
    | existExams -> do
      addMessageI Error MsgCourseDeleteExistExams
      redirect $ CourseR tid ssh csh CExamListR
    | otherwise ->
        deleteR $ (courseDeleteRoute $ Set.singleton cId)
          { drAbort = SomeRoute $ CourseR tid ssh csh CShowR
          , drSuccess = SomeRoute $ TermSchoolCourseListR tid ssh
          }
