use std::sync::Arc;

use eyre::Result;

use foxchat::{fed, s2s::http::RestEvent};
use tracing::{debug, error};

use crate::{app_state::AppState, model::identity_instance::IdentityInstance};

/// Posts an event to a remote instance's inbox.
pub async fn post_rest_event(
    state: Arc<AppState>,
    instance: &IdentityInstance,
    event: RestEvent,
) -> Result<()> {
    debug!("Sending {:?} event to {}'s inbox", &event, &instance.domain);

    match fed::post::<RestEvent, ()>(
        &state.private_key,
        &state.config.domain,
        &instance.domain,
        "/_fox/ident/inbox",
        None,
        &event,
    )
    .await
    {
        Ok(_) => Ok(()),
        Err(e) => {
            error!(
                "Error sending {:?} event to {}'s inbox: {}",
                &event, &instance.domain, e
            );

            return Err(e);
        }
    }
}