1
use std::collections::BTreeMap;
2

            
3
use serde::{Deserialize, Serialize};
4
use serde_json::json;
5

            
6
use crate::core::{
7
    protocol::request_validation::{DbOrUser, NameValidationError, OwnerValidationError},
8
    types::MySQLUser,
9
};
10

            
11
pub type UnlockUsersRequest = Vec<MySQLUser>;
12

            
13
pub type UnlockUsersResponse = BTreeMap<MySQLUser, Result<(), UnlockUserError>>;
14

            
15
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
16
pub enum UnlockUserError {
17
    SanitizationError(NameValidationError),
18
    OwnershipError(OwnerValidationError),
19
    UserDoesNotExist,
20
    UserIsAlreadyUnlocked,
21
    MySqlError(String),
22
}
23

            
24
pub fn print_unlock_users_output_status(output: &UnlockUsersResponse) {
25
    for (username, result) in output {
26
        match result {
27
            Ok(()) => {
28
                println!("User '{}' unlocked successfully.", username);
29
            }
30
            Err(err) => {
31
                println!("{}", err.to_error_message(username));
32
                println!("Skipping...");
33
            }
34
        }
35
        println!();
36
    }
37
}
38

            
39
pub fn print_unlock_users_output_status_json(output: &UnlockUsersResponse) {
40
    let value = output
41
        .iter()
42
        .map(|(name, result)| match result {
43
            Ok(()) => (name.to_string(), json!({ "status": "success" })),
44
            Err(err) => (
45
                name.to_string(),
46
                json!({
47
                  "status": "error",
48
                  "error": err.to_error_message(name),
49
                }),
50
            ),
51
        })
52
        .collect::<serde_json::Map<_, _>>();
53
    println!(
54
        "{}",
55
        serde_json::to_string_pretty(&value)
56
            .unwrap_or("Failed to serialize result to JSON".to_string())
57
    );
58
}
59

            
60
impl UnlockUserError {
61
    pub fn to_error_message(&self, username: &MySQLUser) -> String {
62
        match self {
63
            UnlockUserError::SanitizationError(err) => {
64
                err.to_error_message(username, DbOrUser::User)
65
            }
66
            UnlockUserError::OwnershipError(err) => err.to_error_message(username, DbOrUser::User),
67
            UnlockUserError::UserDoesNotExist => {
68
                format!("User '{}' does not exist.", username)
69
            }
70
            UnlockUserError::UserIsAlreadyUnlocked => {
71
                format!("User '{}' is already unlocked.", username)
72
            }
73
            UnlockUserError::MySqlError(err) => {
74
                format!("MySQL error: {}", err)
75
            }
76
        }
77
    }
78
}