use crate::{ApAddress, ApContext, ApNote, ApObject};
use anyhow::anyhow;
use jdt_maybe_multiple::MaybeMultiple;
use jdt_maybe_reference::MaybeReference;
use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Display, Formatter};

use super::signature::ApSignature;

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
pub enum ApDeleteType {
    #[default]
    #[serde(alias = "delete")]
    Delete,
}

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

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ApDelete {
    #[serde(rename = "@context")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<ApContext>,
    #[serde(rename = "type")]
    pub kind: ApDeleteType,
    pub actor: ApAddress,
    pub id: Option<String>,
    pub object: MaybeReference<ApObject>,
    pub signature: Option<ApSignature>,
    #[serde(skip_serializing_if = "MaybeMultiple::is_none")]
    #[serde(default)]
    pub to: MaybeMultiple<ApAddress>,
    #[serde(skip_serializing_if = "MaybeMultiple::is_none")]
    #[serde(default)]
    pub cc: MaybeMultiple<ApAddress>,
}

impl Display for ApDelete {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Delete[actor: {}, object: {}{}{}{}]",
            self.actor,
            self.object,
            self.id
                .as_ref()
                .map(|id| format!(", id: {}", id))
                .unwrap_or_default(),
            if !self.to.as_ref().is_empty() {
                format!(", to: {:?}", self.to.as_ref())
            } else {
                String::new()
            },
            if !self.cc.as_ref().is_empty() {
                format!(", cc: {:?}", self.cc.as_ref())
            } else {
                String::new()
            }
        )
    }
}

impl ApDelete {
    pub fn new(object: String, actor: ApAddress) -> Self {
        ApDelete {
            context: None,
            kind: ApDeleteType::default(),
            actor,
            id: None,
            object: MaybeReference::Reference(object),
            to: MaybeMultiple::Multiple(vec![ApAddress::get_public()]),
            cc: MaybeMultiple::None,
            signature: None,
        }
    }
}

#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
pub enum ApTombstoneType {
    #[default]
    Tombstone,
}

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

#[derive(Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ApTombstone {
    #[serde(rename = "type")]
    pub kind: ApTombstoneType,
    pub id: String,
    pub atom_uri: Option<String>,
}

impl Debug for ApTombstone {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Tombstone[{}{}]",
            self.id,
            self.atom_uri
                .as_ref()
                .map(|uri| format!(", uri: {}", uri))
                .unwrap_or_default()
        )
    }
}

impl Display for ApTombstone {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "Tombstone[{}]", self.id,)
    }
}

impl TryFrom<ApNote> for ApTombstone {
    type Error = anyhow::Error;

    fn try_from(note: ApNote) -> Result<Self, Self::Error> {
        if let Some(id) = note.id {
            Ok(ApTombstone {
                kind: ApTombstoneType::Tombstone,
                id: id.clone(),
                atom_uri: Some(id),
            })
        } else {
            Err(anyhow!("ApNote must have an ID"))
        }
    }
}

impl TryFrom<ApNote> for ApDelete {
    type Error = anyhow::Error;

    fn try_from(note: ApNote) -> Result<Self, Self::Error> {
        note.id.clone().ok_or(anyhow!("ApNote must have an ID"))?;
        let tombstone = ApTombstone::try_from(note.clone())?;
        Ok(ApDelete {
            context: Some(ApContext::default()),
            actor: note.attributed_to.clone(),
            kind: ApDeleteType::Delete,
            id: None, // This will be set in NewActivity
            object: MaybeReference::Actual(ApObject::Tombstone(tombstone)),
            signature: None,
            to: note.to,
            cc: note.cc,
        })
    }
}
