// 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::{NewBody, post::RequestBody};
use pib_service_core_types::BodyId;

use crate::{Backend, Result};

impl Backend {
    pub(crate) async fn body_post(
        &self,
        user: UserInfo,
        RequestBody(NewBody {
            short_name,
            name,
            website,
            license,
            license_valid_since,
            oparl_since,
            ags,
            rgs,
            contact_email,
            contact_name,
            classification,
            web,
            is_public,
        }): RequestBody,
    ) -> Result<BodyId> {
        self.enforce_permissions(Resource::Body, Method::POST, user.id)
            .await?;

        let mut inventory = self.inventory_provider.get_inventory().await?;
        let body = inventory
            .create_body(pib_service_inventory::NewBody {
                short_name,
                name,
                website,
                license,
                license_valid_since,
                oparl_since,
                ags,
                rgs,
                contact_email,
                contact_name,
                classification,
                web,
                is_public,
            })
            .await?;
        inventory
            .grant_user_body_permission(user.id, body.id)
            .await?;
        Ok(body.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::NewBody, config::oidc::OidcConfig};
    use pib_service_core_types::{BodyId, 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);

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

        let body = pib_service_inventory::Item {
            id: body_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::Body {
                short_name: None,
                name: "Hintertupfing".parse().unwrap(),
                website: None,
                license: None,
                license_valid_since: None,
                oparl_since: None,
                ags: "12345".to_string(),
                rgs: None,
                contact_email: None,
                contact_name: None,
                classification: None,
                web: None,
                is_public: true,
            },
        };

        inventory
            .write()
            .await
            .expect_create_body()
            .with(eq(pib_service_inventory::NewBody {
                short_name: None,
                name: "Hintertupfing".parse().unwrap(),
                website: None,
                license: None,
                license_valid_since: None,
                oparl_since: None,
                ags: "12345".to_string(),
                rgs: None,
                contact_email: None,
                contact_name: None,
                classification: None,
                web: None,
                is_public: true,
            }))
            .times(1)
            .return_once(move |_| Ok(body));
        inventory
            .write()
            .await
            .expect_grant_user_body_permission()
            .with(eq(user_id), eq(body_id))
            .times(1)
            .return_once(move |_, _| Ok(()));

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

        let response = backend
            .handle_body_post(
                user_info,
                RequestBody(NewBody {
                    short_name: None,
                    name: "Hintertupfing".parse().unwrap(),
                    website: None,
                    license: None,
                    license_valid_since: None,
                    oparl_since: None,
                    ags: "12345".to_string(),
                    rgs: None,
                    contact_email: None,
                    contact_name: None,
                    classification: None,
                    web: None,
                    is_public: true,
                }),
            )
            .await
            .unwrap();

        assert_eq!(response, body_id);
    }
}
