// 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::me::profile::{UpdateProfile, patch::RequestBody};
use pib_service_inventory::UpdateUser;

use crate::{Backend, Result};

impl Backend {
    pub(crate) async fn profile_me_patch(
        &self,
        user: UserInfo,
        RequestBody(UpdateProfile { display_name }): RequestBody,
    ) -> Result<()> {
        self.enforce_permissions(Resource::MeProfile, Method::PATCH, user.id)
            .await?;

        let mut inventory = self.inventory_provider.get_inventory().await?;

        inventory
            .update_user(UpdateUser {
                id: user.id,
                sub: None,
                display_name,
                is_superuser: None,
            })
            .await?;

        Ok(())
    }
}

#[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::{config::oidc::OidcConfig, me::profile::UpdateProfile};
    use pib_service_core_types::UserId;
    use pib_service_facade::Service as _;
    use pib_service_test_utils::mock_inventory_with_provider;

    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,
        };

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

        let user = pib_service_inventory::Item {
            id: user_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::User {
                sub: "the-user".to_string(),
                display_name: Some("The User".to_string()),
                is_superuser: false,
            },
        };

        inventory
            .write()
            .await
            .expect_update_user()
            .with(eq(pib_service_inventory::UpdateUser {
                id: user_id,
                sub: None,
                display_name: Some(Some("Another User".to_string())),
                is_superuser: None,
            }))
            .times(1)
            .return_once(move |_| Ok(user));

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

        backend
            .handle_profile_me_patch(
                user_info,
                RequestBody(UpdateProfile {
                    display_name: Some(Some("Another User".to_string())),
                }),
            )
            .await
            .unwrap();
    }
}
