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 LockUsersRequest = Vec<MySQLUser>;
12

            
13
pub type LockUsersResponse = BTreeMap<MySQLUser, Result<(), LockUserError>>;
14

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

            
24
pub fn print_lock_users_output_status(output: &LockUsersResponse) {
25
    for (username, result) in output {
26
        match result {
27
            Ok(()) => {
28
                println!("User '{}' locked 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_lock_users_output_status_json(output: &LockUsersResponse) {
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 LockUserError {
61
    pub fn to_error_message(&self, username: &MySQLUser) -> String {
62
        match self {
63
            LockUserError::SanitizationError(err) => err.to_error_message(username, DbOrUser::User),
64
            LockUserError::OwnershipError(err) => err.to_error_message(username, DbOrUser::User),
65
            LockUserError::UserDoesNotExist => {
66
                format!("User '{}' does not exist.", username)
67
            }
68
            LockUserError::UserIsAlreadyLocked => {
69
                format!("User '{}' is already locked.", username)
70
            }
71
            LockUserError::MySqlError(err) => {
72
                format!("MySQL error: {}", err)
73
            }
74
        }
75
    }
76
}