module Network.Transport.QUIC.Internal.Configuration (
    mkClientConfig,
    mkServerConfig,

    -- * Re-export to generate credentials
    Credential,
    TLS.credentialLoadX509,
) where

import Data.List.NonEmpty (NonEmpty)
import Data.List.NonEmpty qualified as NonEmpty
import Network.QUIC.Client (ClientConfig(ccValidate), ccPortName, ccServerName, defaultClientConfig)
import Network.QUIC.Internal (ServerConfig, ccCredentials)
import Network.QUIC.Server (ServerConfig (scCredentials, scSessionManager), defaultServerConfig)
import Network.Socket (HostName, ServiceName)
import Network.TLS (Credential, Credentials (Credentials))
import Network.Transport.QUIC.Internal.TLS qualified as TLS

mkClientConfig ::
    HostName ->
    ServiceName ->
    NonEmpty Credential ->
    Bool -> -- ^ Validate credentials
    IO ClientConfig
mkClientConfig :: HostName
-> HostName -> NonEmpty Credential -> Bool -> IO ClientConfig
mkClientConfig HostName
host HostName
port NonEmpty Credential
creds Bool
validate = do
    ClientConfig -> IO ClientConfig
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ClientConfig -> IO ClientConfig)
-> ClientConfig -> IO ClientConfig
forall a b. (a -> b) -> a -> b
$
        ClientConfig
defaultClientConfig
            { ccServerName = host
            , ccPortName = port
            , ccValidate = validate
            , ccCredentials = Credentials (NonEmpty.toList creds)
            }

mkServerConfig ::
    NonEmpty Credential ->
    IO ServerConfig
mkServerConfig :: NonEmpty Credential -> IO ServerConfig
mkServerConfig NonEmpty Credential
creds = do
    SessionManager
tlsSessionManager <- IO SessionManager
TLS.sessionManager

    ServerConfig -> IO ServerConfig
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ServerConfig -> IO ServerConfig)
-> ServerConfig -> IO ServerConfig
forall a b. (a -> b) -> a -> b
$
        ServerConfig
defaultServerConfig
            { scSessionManager = tlsSessionManager
            , scCredentials = Credentials (NonEmpty.toList creds)
            }