// SPDX-FileCopyrightText: Politik im Blick developers
// SPDX-FileCopyrightText: Wolfgang Silbermayr <wolfgang@silbermayr.at>
//
// SPDX-License-Identifier: AGPL-3.0-or-later OR EUPL-1.2

use std::sync::Arc;

use pib_service_api_auth::ApiAuth;
use pib_service_facade::Service;
use tokio::net::ToSocketAddrs;

mod auth;
mod error;
mod router;

use router::router;

use auth::Auth;
pub use error::Error;

pub type Result<T, E = Error> = std::result::Result<T, E>;

pub async fn run<A: ToSocketAddrs, E: Into<pib_service_facade::Error> + Send + Sync + 'static>(
    addrs: A,
    service: Arc<dyn Service<E>>,
    auth: Arc<dyn ApiAuth>,
) -> anyhow::Result<()>
where
    crate::Error: From<E>,
{
    let auth_layer = { Auth::new(auth) };

    let app = router(auth_layer, service).await;
    let listener = tokio::net::TcpListener::bind(addrs).await?;
    axum::serve(listener, app).await?;
    Ok(())
}
