-- This file is part of the Wire Server implementation.
--
-- Copyright (C) 2025 Wire Swiss GmbH <opensource@wire.com>
--
-- This program is free software: you can redistribute it and/or modify it under
-- the terms of the GNU Affero General Public License as published by the Free
-- Software Foundation, either version 3 of the License, or (at your option) any
-- later version.
--
-- This program is distributed in the hope that it will be useful, but WITHOUT
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
-- details.
--
-- You should have received a copy of the GNU Affero General Public License along
-- with this program. If not, see <https://www.gnu.org/licenses/>.

module Test.Spar.Scim.UserSpec where

import Arbitrary ()
import Control.Monad.Except (runExceptT)
import Data.Handle (parseHandle)
import Data.HavePendingInvitations
import Data.Id
import Imports
import Polysemy
import Polysemy.TinyLog
import Spar.Scim.User (deleteScimUser)
import Spar.Sem.SAMLUserStore
import Spar.Sem.SAMLUserStore.Mem (samlUserStoreToMem)
import System.Logger (Msg)
import Test.Hspec
import Test.QuickCheck
import Web.Scim.Schema.Error
import Wire.API.User
import Wire.API.User.Scim
import Wire.BrigAPIAccess
import Wire.IdPConfigStore
import Wire.IdPConfigStore.Mem (idPToMem)
import Wire.IdPConfigStore.Orphans ()
import qualified Wire.ScimExternalIdStore as ScimExternalIdStore
import Wire.ScimExternalIdStore.Mem (scimExternalIdStoreToMem)
import Wire.ScimUserTimesStore
import Wire.ScimUserTimesStore.Mem (scimUserTimesStoreToMem)
import Wire.Sem.Logger.TinyLog (discardTinyLogs)

spec :: Spec
spec = describe "deleteScimUser" $ do
  it "returns no error when the account was deleted for the first time (or partially)" $ do
    tokenInfo <- generate arbitrary
    acc <- someActiveUser tokenInfo
    r <-
      interpretWithBrigAPIAccessMock
        (mockBrig (withActiveUser acc))
        (deleteUserAndAssertDeletionInSpar acc tokenInfo)
    r `shouldBe` Right ()
  it "is idempotent" $ do
    tokenInfo <- generate arbitrary
    acc <- someActiveUser tokenInfo
    r <-
      interpretWithBrigAPIAccessMock
        (mockBrig (withActiveUser acc))
        (deleteUserAndAssertDeletionInSpar acc tokenInfo)
    r `shouldBe` Right ()
  it "works if there never was an account" $ do
    uid <- generate arbitrary
    tokenInfo <- generate arbitrary
    r <-
      interpretWithBrigAPIAccessMock
        (mockBrig (const Nothing))
        (runExceptT $ deleteScimUser tokenInfo uid)
    r `shouldBe` Right ()
  it "returns no error when there was a partially deleted account" $ do
    uid <- generate arbitrary
    tokenInfo <- generate arbitrary
    r <-
      interpretWithBrigAPIAccessMock
        (mockBrig (const Nothing))
        (runExceptT $ deleteScimUser tokenInfo uid)
    r `shouldBe` Right ()

deleteUserAndAssertDeletionInSpar ::
  forall (r :: EffectRow).
  ( Members
      '[ Logger (Msg -> Msg),
         BrigAPIAccess,
         ScimExternalIdStore.ScimExternalIdStore,
         ScimUserTimesStore,
         SAMLUserStore,
         IdPConfigStore,
         Embed IO
       ]
      r
  ) =>
  User ->
  ScimTokenInfo ->
  Sem r (Either ScimError ())
deleteUserAndAssertDeletionInSpar acc tokenInfo = do
  let tid = tokenInfo.stiTeam
      email = (fromJust . emailIdentity . fromJust . userIdentity) acc
      uid = userId acc
  ScimExternalIdStore.insert tid (fromEmail email) uid
  r <- runExceptT $ deleteScimUser tokenInfo uid
  lr <- ScimExternalIdStore.lookup tid (fromEmail email)
  liftIO $ lr `shouldBe` Nothing
  pure r

type EffsWithoutBrigAPIAccess =
  '[ IdPConfigStore,
     SAMLUserStore,
     ScimUserTimesStore,
     ScimExternalIdStore.ScimExternalIdStore,
     Logger (Msg -> Msg),
     Embed IO,
     Final IO
   ]

interpretWithBrigAPIAccessMock ::
  ( Sem (BrigAPIAccess ': EffsWithoutBrigAPIAccess) a ->
    Sem EffsWithoutBrigAPIAccess a
  ) ->
  Sem (BrigAPIAccess ': EffsWithoutBrigAPIAccess) a ->
  IO a
interpretWithBrigAPIAccessMock mock =
  runFinal
    . embedToFinal @IO
    . discardTinyLogs
    . ignoringState scimExternalIdStoreToMem
    . ignoringState scimUserTimesStoreToMem
    . ignoringState samlUserStoreToMem
    . ignoringState idPToMem
    . mock

ignoringState :: (Functor f) => (a -> f (c, b)) -> a -> f b
ignoringState f = fmap snd . f

mockBrig ::
  forall (r :: EffectRow) a.
  (Member (Embed IO) r) =>
  (UserId -> Maybe User) ->
  Sem (BrigAPIAccess ': r) a ->
  Sem r a
mockBrig lookup_user = interpret $ \case
  (GetAccount WithPendingInvitations uid) -> pure $ lookup_user uid
  (Wire.BrigAPIAccess.DeleteUser _) -> pure ()
  _ -> do
    liftIO $ expectationFailure $ "Unexpected effect (call to brig)"
    error "Throw error here to avoid implementation of all cases."

withActiveUser :: User -> UserId -> Maybe User
withActiveUser acc uid =
  if uid == userId acc
    then Just acc
    else Nothing

someActiveUser :: ScimTokenInfo -> IO User
someActiveUser tokenInfo = do
  user <- generate arbitrary
  pure $
    user
      { userDisplayName = Name "Some User",
        userEmailUnvalidated = Nothing,
        userAccentId = defaultAccentId,
        userStatus = Active,
        userPict = noPict,
        userAssets = [],
        userHandle = parseHandle "some-handle",
        userIdentity = (Just . EmailIdentity . fromJust . emailAddressText) "someone@wire.com",
        userTeam = Just $ tokenInfo.stiTeam
      }
