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

            
13
pub type CreateUsersResponse = BTreeMap<MySQLUser, Result<(), CreateUserError>>;
14

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

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

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

            
59
impl CreateUserError {
60
    pub fn to_error_message(&self, username: &MySQLUser) -> String {
61
        match self {
62
            CreateUserError::SanitizationError(err) => {
63
                err.to_error_message(username, DbOrUser::User)
64
            }
65
            CreateUserError::OwnershipError(err) => err.to_error_message(username, DbOrUser::User),
66
            CreateUserError::UserAlreadyExists => {
67
                format!("User '{}' already exists.", username)
68
            }
69
            CreateUserError::MySqlError(err) => {
70
                format!("MySQL error: {}", err)
71
            }
72
        }
73
    }
74
}