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
}