// 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 pib_service_api_auth::user::UserInfo;
use pib_service_api_types::body::by_id::meeting::by_id::get::ResponseBody;
use pib_service_core_types::{BodyId, MeetingId};
use pib_service_facade::Service;

use axum::{
    Extension, Json,
    extract::{Path, State},
};

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((body_id, meeting_id)): Path<(BodyId, MeetingId)>,
) -> Result<Json<ResponseBody>>
where
    crate::Error: From<E>,
{
    Ok(Json(
        service
            .handle_body_by_id_meeting_by_id_get(user, body_id, meeting_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::body::by_id::meeting::Meeting;
    use pib_service_core_types::{BodyId, MeetingId, OrganizationId, 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 body_id = BodyId::from_u128(0x9595);
        let meeting_id = MeetingId::from_u128(0x1717);

        let response_body = ResponseBody(Meeting {
            id: MeetingId::from_u128(0x3344),
            created: "2026-04-07T05:06:07+01:00".parse().unwrap(),
            modified: "2026-04-08T05:06:07+01:00".parse().unwrap(),
            body_id,
            name: Some("Jahreshauptversammlung".parse().unwrap()),
            license: None,
            organization_id: OrganizationId::from_u128(0x8844),
            meeting_state: None,
            start: None,
            end: None,
            web: None,
        });

        {
            let response_body = response_body.clone();
            service
                .expect_handle_body_by_id_meeting_by_id_get()
                .times(1)
                .with(eq(user_info), eq(body_id), eq(meeting_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((body_id, meeting_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 body_id = BodyId::from_u128(0x9696);
        let meeting_id = MeetingId::from_u128(0x2828);

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

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