use anyhow::{Result, anyhow};
use reqwest::Client;
use serde::Serialize;

pub struct Telegram {
    url: String,
    chat_id: i64,
}

#[derive(Serialize)]
struct TelegramMessage {
    chat_id: i64,
    text: String,
}

impl Telegram {
    pub fn set_url(token: &str, chat_id: &str) -> Result<Self, anyhow::Error> {
        let chat_id_num: i64 = chat_id.parse()?;
        let url = format!("https://api.telegram.org/bot{}/sendMessage", token);

        Ok(Telegram {
            url,
            chat_id: chat_id_num,
        })
    }

    pub async fn send_message(&self, message_string: &str) -> Result<(), anyhow::Error> {
        let message = TelegramMessage {
            chat_id: self.chat_id,
            text: message_string.to_string(),
        };

        let client = Client::new();
        let response = client.post(&self.url).json(&message).send().await?;

        if !response.status().is_success() {
            return Err(anyhow!(
                "Failed to send message. Status: {}",
                response.status()
            ));
        }

        Ok(())
    }
}

pub async fn send_telegram_message(
    message: &String,
    telegram_token: &str,
    telegram_channel_id: &str,
) -> Result<(), anyhow::Error> {
    let telegram = Telegram::set_url(&telegram_token, &telegram_channel_id)?;
    telegram.send_message(&message).await?;

    Ok(())
}
