//! The type that represents a response of `chat.postMessage`.
//!
//! <https://api.slack.com/methods/chat.postMessage>

use crate::generated::chat_post_message::ChatPostMessageResponse as Generated;
use crate::Error;
use serde::Deserialize;

/// The type that represents a response of `chat.postMessage`.
///
/// <https://api.slack.com/methods/chat.postMessage>
#[derive(Debug, Deserialize)]
pub struct ChatPostMessageResponse(Generated);

impl ChatPostMessageResponse {
    /// Converts to generated type.
    pub fn into_inner(self) -> Generated {
        self.0
    }

    /// Takes `channel`.
    pub fn channel(&self) -> Option<&str> {
        self.0.channel.as_deref()
    }

    /// Takes `ts`.
    pub fn ts(&self) -> Option<&str> {
        self.0.ts.as_deref()
    }
}

impl TryFrom<serde_json::Value> for ChatPostMessageResponse {
    type Error = Error;

    fn try_from(value: serde_json::Value) -> Result<Self, Self::Error> {
        serde_json::from_value(value).map_err(Error::DeserializeJson)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_successful() {
        let testdata = r#"
        {
            "ok": true,
            "channel": "C123ABC456",
            "ts": "1503435956.000247",
            "message": {
                "text": "Here's a message for you",
                "username": "ecto1",
                "bot_id": "B123ABC456",
                "attachments": [
                    {
                        "text": "This is an attachment",
                        "id": 1,
                        "fallback": "This is an attachment's fallback"
                    }
                ],
                "type": "message",
                "subtype": "bot_message",
                "ts": "1503435956.000247"
            }
        }"#;

        let deserialized: ChatPostMessageResponse = serde_json::from_str(testdata).unwrap();
        assert_eq!(deserialized.channel().unwrap(), "C123ABC456");
        assert_eq!(deserialized.ts().unwrap(), "1503435956.000247");
    }
}
