1
use std::collections::BTreeMap;
2

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

            
7
use crate::core::{protocol::request_validation::ValidationError, types::DbOrUser};
8

            
9
pub type CheckAuthorizationRequest = Vec<DbOrUser>;
10

            
11
pub type CheckAuthorizationResponse = BTreeMap<DbOrUser, Result<(), CheckAuthorizationError>>;
12

            
13
#[derive(Error, Debug, Clone, PartialEq, Serialize, Deserialize)]
14
#[error("Validation error: {0}")]
15
pub struct CheckAuthorizationError(#[from] pub ValidationError);
16

            
17
pub fn print_check_authorization_output_status(output: &CheckAuthorizationResponse) {
18
    for (db_or_user, result) in output {
19
        match result {
20
            Ok(()) => {
21
                println!("'{}': OK", db_or_user.name());
22
            }
23
            Err(err) => {
24
                eprintln!(
25
                    "'{}': {}",
26
                    db_or_user.name(),
27
                    err.to_error_message(db_or_user)
28
                );
29
            }
30
        }
31
    }
32
}
33

            
34
pub fn print_check_authorization_output_status_json(output: &CheckAuthorizationResponse) {
35
    let value = output
36
        .iter()
37
        .map(|(db_or_user, result)| match result {
38
            Ok(()) => (
39
                db_or_user.name().to_string(),
40
                json!({ "status": "success" }),
41
            ),
42
            Err(err) => (
43
                db_or_user.name().to_string(),
44
                json!({
45
                  "status": "error",
46
                  "type": err.error_type(),
47
                  "error": err.to_error_message(db_or_user),
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 CheckAuthorizationError {
60
    #[must_use]
61
    pub fn to_error_message(&self, db_or_user: &DbOrUser) -> String {
62
        self.0.to_error_message(db_or_user)
63
    }
64

            
65
    #[must_use]
66
    pub fn error_type(&self) -> String {
67
        self.0.error_type()
68
    }
69
}
70

            
71
#[cfg(test)]
72
mod tests {
73
    use crate::core::protocol::request_validation::NameValidationError;
74

            
75
    use super::*;
76

            
77
    #[test]
78
1
    fn test_serialize_deserialize_request() {
79
1
        let request: CheckAuthorizationRequest = vec![
80
1
            DbOrUser::Database("test_db".into()),
81
1
            DbOrUser::User("test_user".into()),
82
        ];
83

            
84
1
        let json = serde_json::to_string_pretty(&request).unwrap();
85
1
        println!("Serialized request:\n{}", json);
86

            
87
1
        let deserialized: CheckAuthorizationRequest = serde_json::from_str(&json).unwrap();
88
1
        assert_eq!(request, deserialized);
89
1
    }
90

            
91
    #[test]
92
1
    fn test_serialize_deserialize_response() {
93
1
        let response: CheckAuthorizationResponse = BTreeMap::from([
94
1
            (DbOrUser::Database("test_db".into()), Ok(())),
95
1
            (
96
1
                DbOrUser::User("test_user".into()),
97
1
                Err(CheckAuthorizationError(
98
1
                    ValidationError::NameValidationError(NameValidationError::TooLong),
99
1
                )),
100
1
            ),
101
1
        ]);
102

            
103
1
        let json = serde_json::to_string_pretty(&response).unwrap();
104
1
        println!("Serialized response:\n{}", json);
105

            
106
1
        let deserialized: CheckAuthorizationResponse = serde_json::from_str(&json).unwrap();
107
1
        assert_eq!(response, deserialized);
108
1
    }
109
}