use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Display, Formatter};

use crate::{ApAddress, ApContext};

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
pub enum ApBlockType {
    #[default]
    #[serde(alias = "block")]
    Block,
}

impl Display for ApBlockType {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        Debug::fmt(self, f)
    }
}

#[derive(Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ApBlock {
    #[serde(rename = "@context")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<ApContext>,
    #[serde(rename = "type")]
    pub kind: ApBlockType,
    pub actor: ApAddress,
    pub id: Option<String>,
    pub object: String,
}

impl Debug for ApBlock {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Block[by: {}, obj: {}{}]",
            self.actor,
            self.object,
            self.id
                .as_ref()
                .map(|id| format!(", id: {}", id))
                .unwrap_or_default()
        )
    }
}

impl Display for ApBlock {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Block[{}]",
            self.id
                .as_ref()
                .map(|id| format!("id: {}", id))
                .unwrap_or("no id".to_string())
        )
    }
}
