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

use crate::{Backend, Result};

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

        RequestBody(NewOrganization {
            name,
            short_name,
            classification,
            start_date,
            end_date,
            website,
            color,
        }): RequestBody,
    ) -> Result<OrganizationId> {
        self.enforce_permissions(
            Resource::BodyByIdOrganization { body_id },
            Method::POST,
            user.id,
        )
        .await?;

        let mut inventory = self.inventory_provider.get_inventory().await?;
        let organization = inventory
            .create_organization(pib_service_inventory::NewOrganization {
                body_id,
                name,
                short_name,
                classification,
                start_date,
                end_date,
                website,
                color,
            })
            .await?;
        Ok(organization.id)
    }
}

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

    use mockall::predicate::eq;
    use pib_oparl_extensions::Color;
    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::organization::NewOrganization, config::oidc::OidcConfig,
    };
    use pib_service_core_types::{BodyId, 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 organization_id = OrganizationId::from_u128(0x9999);

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

        let organization = pib_service_inventory::Item {
            id: organization_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::Organization {
                body_id,
                name: "Gemeinderat".into(),
                short_name: None,
                start_date: None,
                end_date: None,
                website: None,
                membership: vec![],
                classification: None,
                color: Some(Color {
                    r: 0x77,
                    g: 0x88,
                    b: 0x99,
                }),
            },
        };

        inventory
            .write()
            .await
            .expect_create_organization()
            .with(eq(pib_service_inventory::NewOrganization {
                body_id,
                name: "Gemeinderat".into(),
                short_name: None,
                start_date: None,
                end_date: None,
                website: None,
                classification: None,
                color: Some(Color {
                    r: 0x77,
                    g: 0x88,
                    b: 0x99,
                }),
            }))
            .times(1)
            .return_once(move |_| Ok(organization));

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

        let response = backend
            .handle_body_by_id_organization_post(
                user_info,
                body_id,
                RequestBody(NewOrganization {
                    name: "Gemeinderat".into(),
                    short_name: None,
                    start_date: None,
                    end_date: None,
                    website: None,
                    classification: None,
                    color: Some(Color {
                        r: 0x77,
                        g: 0x88,
                        b: 0x99,
                    }),
                }),
            )
            .await
            .unwrap();

        assert_eq!(response, organization_id);
    }
}
