// 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 pib_service_api_auth::user::UserInfo;
use pib_service_api_permissions::{Method, Resource};
use pib_service_api_types::body::by_id::meeting::{NewMeeting, post::RequestBody};
use pib_service_core_types::{BodyId, MeetingId};

use crate::{Backend, Result};

impl Backend {
    pub(crate) async fn body_by_id_meeting_post(
        &self,
        user: UserInfo,
        body_id: BodyId,

        RequestBody(NewMeeting {
            organization_id,
            name,
            meeting_state,
            keyword,
            start,
            end,
            license,
            web,
        }): RequestBody,
    ) -> Result<MeetingId> {
        self.enforce_permissions(Resource::BodyByIdMeeting { body_id }, Method::POST, user.id)
            .await?;

        let state = meeting_state.parse()?;
        let mut inventory = self.inventory_provider.get_inventory().await?;
        let meeting = inventory
            .create_meeting(pib_service_inventory::NewMeeting {
                body_id,
                organization_id,
                start,
                end,
                name,
                state,
                keyword,
                license,
                web,
            })
            .await?;
        Ok(meeting.id)
    }
}

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

    use mockall::predicate::eq;
    use pib_service_api_auth::user::{Issuer, OidcSub, UserInfo};
    use pib_service_api_permissions::{Admission, Method, MockPermissions, Resource};
    use pib_service_api_types::{body::by_id::meeting::NewMeeting, config::oidc::OidcConfig};
    use pib_service_core_types::{BodyId, MeetingId, OrganizationId, UserId};
    use pib_service_facade::Service as _;
    use pib_service_test_utils::mock_inventory_with_provider;
    use pretty_assertions::assert_eq;

    use super::RequestBody;
    use crate::Backend;

    #[tokio::test]
    async fn endpoint() {
        let (inventory, provider) = mock_inventory_with_provider();
        let mut permissions = MockPermissions::new();
        let oidc = OidcConfig {
            issuer: "https://auth.example.com/".to_string(),
            client_id: "abcdef".to_string(),
            client_secret: "ghijkl".to_string(),
        };

        let user_id = UserId::from_u128(0x4444);
        let user_info = UserInfo {
            id: user_id,
            issuer: Issuer("https://auth.example.com".to_string()),
            sub: OidcSub("theuser".to_string()),
            display_name: Some("The User".to_string()),
            is_superuser: false,
        };

        let body_id = BodyId::from_u128(0x7777);
        let meeting_id = MeetingId::from_u128(0x5555);
        let organization_id = OrganizationId::from_u128(0x9999);

        permissions
            .expect_request_permission()
            .with(
                eq(Resource::BodyByIdMeeting { body_id }),
                eq(Method::POST),
                eq(user_id),
            )
            .times(1)
            .return_once(|_, _, _| Ok(Admission::Allow));

        let meeting = pib_service_inventory::Item {
            id: meeting_id,
            created: "2026-04-07T05:06:07+01:00".parse().unwrap(),
            modified: "2026-04-08T05:06:07+01:00".parse().unwrap(),
            value: pib_service_inventory::Meeting {
                body_id,
                organization_id,
                name: Some("Konstituierende Sitzung".into()),
                start: None,
                end: None,
                meeting_state: pib_service_inventory::MeetingState::Invited,
                agenda_item: vec![],
                keyword: vec![],
                web: None,
                license: None,
            },
        };

        inventory
            .write()
            .await
            .expect_create_meeting()
            .with(eq(pib_service_inventory::NewMeeting {
                body_id,
                organization_id,
                name: Some("Konstituierende Sitzung".parse().unwrap()),
                start: None,
                end: None,
                state: pib_service_inventory::MeetingState::Invited,
                keyword: Some(vec![]),
                web: None,
                license: None,
            }))
            .times(1)
            .return_once(move |_| Ok(meeting));

        let backend = Backend::new(provider, Arc::new(permissions), oidc, None);

        let response = backend
            .handle_body_by_id_meeting_post(
                user_info,
                body_id,
                RequestBody(NewMeeting {
                    organization_id,
                    name: Some("Konstituierende Sitzung".parse().unwrap()),
                    start: None,
                    end: None,
                    meeting_state: pib_service_inventory::MeetingState::Invited
                        .as_str()
                        .to_string(),
                    keyword: Some(vec![]),
                    web: None,
                    license: None,
                }),
            )
            .await
            .unwrap();

        assert_eq!(response, meeting_id);
    }
}
