use poise::{serenity_prelude::CreateEmbed, CreateReply};
use serde::{Deserialize, Serialize};

use crate::{
    consts::THEME_COLOR,
    utils::{footer, Extract, Recordable},
    Context, Error,
};

#[derive(Serialize, Deserialize, Extract)]
pub struct Options;

impl Recordable for Options {
    async fn run(self, ctx: Context<'_>) -> Result<(), Error> {
        let footer = footer(ctx);

        ctx.send(
            CreateReply::default().ephemeral(true).embed(
                CreateEmbed::new()
                    .title("Dashboard")
                    .description("**https://beta.reminder-bot.com/dashboard**")
                    .footer(footer)
                    .color(*THEME_COLOR),
            ),
        )
        .await?;

        Ok(())
    }
}

/// Get the link to the web dashboard
#[poise::command(slash_command, rename = "dashboard", identifying_name = "dashboard")]
#[cfg(not(test))]
pub async fn command(ctx: Context<'_>) -> Result<(), Error> {
    (Options {}).run(ctx).await
}

#[cfg(test)]
mod test {
    use std::env;

    use sqlx::Pool;
    use tokio::sync::{broadcast, Mutex};

    use crate::{
        commands::dashboard::Options,
        test::{MockCache, TestContext, TestData},
        utils::Recordable,
        Data,
    };

    #[tokio::test]
    async fn dashboard_command() {
        let (tx, _rx) = broadcast::channel(16);
        let database = Pool::connect(&env::var("DATABASE_URL").expect("No database URL provided"))
            .await
            .unwrap();

        let ctx = TestContext {
            data: &Data { database, popular_timezones: vec![], _broadcast: tx },
            cache: &MockCache {},
            test_data: &Mutex::new(TestData { replies: vec![] }),
            shard_id: 0,
        };

        let res = (Options {}).run(ctx).await;

        assert!(res.is_ok(), "command OK");
        assert_eq!(ctx.test_data.lock().await.replies.len(), 1, "one message sent");
        assert!(
            ctx.sent_content()
                .await
                .contains(&String::from("**https://beta.reminder-bot.com/dashboard**")),
            "content correct"
        );
    }
}
