// 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 crate::Result;
use axum::{
    Extension, Json,
    extract::{Path, State},
};
use pib_service_api_auth::user::UserInfo;
use pib_service_api_types::user::by_id::get::ResponseBody;
use pib_service_core_types::UserId;
use pib_service_facade::Service;

pub(crate) async fn handle<E: Into<pib_service_facade::Error> + Send + Sync>(
    State(service): State<Arc<dyn Service<E>>>,
    Extension(user): Extension<UserInfo>,
    Path(user_id): Path<UserId>,
) -> Result<Json<ResponseBody>>
where
    crate::Error: From<E>,
{
    Ok(Json(service.handle_user_by_id_get(user, user_id).await?))
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use crate::Error;

    use super::{ResponseBody, handle};
    use axum::{
        Extension,
        extract::{Path, State},
    };
    use mockall::predicate::eq;
    use pib_service_api_auth::user::{Issuer, OidcSub, UserInfo};
    use pib_service_api_types::user::User;
    use pib_service_core_types::UserId;
    use pib_service_facade::MockService;
    use pretty_assertions::{assert_eq, assert_matches};

    #[tokio::test]
    async fn valid() {
        let mut service = MockService::<pib_service_facade::Error>::new();

        let user_info = UserInfo {
            id: UserId::from_u128(0x5555),
            issuer: Issuer(String::from("http://auth.example.com")),
            sub: OidcSub("max.mustermann".to_string()),
            display_name: Some("Max Mustermann".to_string()),
            is_superuser: false,
        };
        let user_id = UserId::from_u128(0x9595);

        let response_body = ResponseBody(User {
            id: UserId::from_u128(0x2211),
            sub: "1337".to_string(),
            display_name: Some("Alice".to_string()),
            is_superuser: false,
        });

        {
            let response_body = response_body.clone();
            service
                .expect_handle_user_by_id_get()
                .times(1)
                .with(eq(user_info), eq(user_id))
                .return_once(move |_, _| Ok(response_body));
        }

        let response = handle(
            State(Arc::new(service)),
            Extension(UserInfo {
                id: UserId::from_u128(0x5555),
                issuer: Issuer("http://auth.example.com".to_string()),
                sub: OidcSub("max.mustermann".to_string()),
                display_name: Some("Max Mustermann".to_string()),
                is_superuser: false,
            }),
            Path(user_id),
        )
        .await
        .unwrap();
        assert_eq!(response.0, response_body);
    }

    #[tokio::test]
    async fn invalid() {
        let mut service = MockService::new();

        let user_info = UserInfo {
            id: UserId::from_u128(0x5555),
            issuer: Issuer(String::from("http://auth.example.com")),
            sub: OidcSub("max.mustermann".to_string()),
            display_name: Some("Max Mustermann".to_string()),
            is_superuser: false,
        };
        let user_id = UserId::from_u128(0x9696);

        service
            .expect_handle_user_by_id_get()
            .times(1)
            .with(eq(user_info.clone()), eq(user_id))
            .return_once(|_, _| Err(pib_service_facade::Error::NotFound));

        assert_matches!(
            handle(
                State(Arc::new(service)),
                Extension(user_info.clone()),
                Path(user_id),
            )
            .await,
            Err(Error::Service {
                source: pib_service_facade::Error::NotFound
            })
        );
    }
}
