{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}

-- This file is part of the Wire Server implementation.
--
-- Copyright (C) 2022 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/>.

-- | 'Cql' instances for Spar types, as well as conversion functions used in "Spar.Data"
-- (which does the actual database work).
module Spar.Data.Instances () where

import Cassandra as Cas
import Data.ByteString (toStrict)
import Data.ByteString.Conversion (fromByteString, toByteString)
import Data.Functor.Alt (Alt ((<!>)))
import qualified Data.Text.Encoding as T
import Data.Text.Encoding.Error
import Imports
import Wire.API.User.Scim

deriving instance Cql ScimToken

instance Cql ScimTokenHash where
  ctype = Tagged TextColumn
  toCql = CqlText . T.decodeUtf8With lenientDecode . toStrict . toByteString
  fromCql (CqlText t) =
    maybe
      (Left "ScimTokenHash: parse error")
      Right
      (fromByteString . T.encodeUtf8 $ t)
  fromCql _ = Left "ScimTokenHash: expected CqlText"

instance Cql ScimTokenLookupKey where
  ctype = Tagged TextColumn
  toCql = \case
    ScimTokenLookupKeyHashed h -> toCql h
    ScimTokenLookupKeyPlaintext t -> toCql t
  fromCql s@(CqlText _) =
    (ScimTokenLookupKeyHashed <$> fromCql s)
      <!> (ScimTokenLookupKeyPlaintext <$> fromCql s)
  fromCql _ = Left "ScimTokenLookupKey: expected CqlText"
