//! `rebuild gateway` command parsing.
//!
//! The old `rebuild` command (in-container cargo build + restart of a sled)
//! was removed: fleet binary updates go through `release` + `upgrade all`
//! exclusively.  Only the gateway self-rebuild command remains here.

use crate::chat::util::strip_bot_mention;

/// A parsed rebuild command.
#[derive(Debug, PartialEq)]
pub struct RebuildCommand;

/// Parse a "rebuild gateway" command from a raw message body.
///
/// Returns `Some(RebuildCommand)` only when the stripped message begins with
/// "rebuild gateway" (case-insensitive).
pub fn extract_rebuild_gateway_command(
    message: &str,
    bot_name: &str,
    bot_user_id: &str,
) -> Option<RebuildCommand> {
    let stripped = strip_bot_mention(message, bot_name, bot_user_id);
    let trimmed = stripped
        .trim()
        .trim_start_matches(|c: char| !c.is_alphanumeric());

    let (cmd, rest) = trimmed.split_once(char::is_whitespace)?;

    if !cmd.eq_ignore_ascii_case("rebuild") {
        return None;
    }

    let qualifier = rest
        .trim()
        .trim_start_matches(|c: char| !c.is_alphanumeric());
    let first_word = match qualifier.split_once(char::is_whitespace) {
        Some((w, _)) => w,
        None => qualifier,
    };

    if first_word.eq_ignore_ascii_case("gateway") {
        Some(RebuildCommand)
    } else {
        None
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn extract_gateway_rebuild() {
        let cmd =
            extract_rebuild_gateway_command("Timmy rebuild gateway", "Timmy", "@timmy:home.local");
        assert_eq!(cmd, Some(RebuildCommand));
    }

    #[test]
    fn plain_rebuild_is_not_gateway_rebuild() {
        let cmd = extract_rebuild_gateway_command("Timmy rebuild", "Timmy", "@timmy:home.local");
        assert_eq!(cmd, None);
    }

    #[test]
    fn non_rebuild_returns_none() {
        let cmd = extract_rebuild_gateway_command("Timmy status", "Timmy", "@timmy:home.local");
        assert_eq!(cmd, None);
    }
}
