use crate::controllers::backup_controller::BackupControllerError;
use actix_web::http::StatusCode;
use actix_web::{HttpResponse, ResponseError};
use std::error::Error;
use zip::result::ZipError;

pub mod accounts_controller;
pub mod auth_controller;
pub mod backup_controller;
pub mod files_controller;
pub mod inbox_controller;
pub mod movement_controller;
pub mod server_controller;
pub mod static_controller;
pub mod stats_controller;
pub mod tokens_controller;

#[derive(thiserror::Error, Debug)]
pub enum HttpFailure {
    #[error("this resource requires higher privileges")]
    Forbidden,
    #[error("this resource was not found")]
    NotFound,
    #[error("Actix web error")]
    ActixError(#[from] actix_web::Error),
    #[error("an unhandled session insert error occurred")]
    SessionInsertError(#[from] actix_session::SessionInsertError),
    #[error("an unhandled session error occurred")]
    SessionError(#[from] actix_session::SessionGetError),
    #[error("an unspecified open id error occurred: {0}")]
    OpenID(Box<dyn Error>),
    #[error("an unspecified internal error occurred: {0}")]
    InternalError(#[from] anyhow::Error),
    #[error("a serde_json error occurred: {0}")]
    SerdeJsonError(#[from] serde_json::error::Error),
    #[error("a zip manipulation error occurred: {0}")]
    ZipError(#[from] ZipError),
    #[error("a standard I/O manipulation error occurred: {0}")]
    StdIoError(#[from] std::io::Error),
    #[error("an error occurred while performing backup/recovery operation: {0}")]
    BackupControllerError(#[from] BackupControllerError),
    #[error("an error while encoding Excel document: {0}")]
    XslxError(#[from] rust_xlsxwriter::XlsxError),
}

impl ResponseError for HttpFailure {
    fn status_code(&self) -> StatusCode {
        match &self {
            Self::Forbidden => StatusCode::FORBIDDEN,
            Self::NotFound => StatusCode::NOT_FOUND,
            _ => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }

    fn error_response(&self) -> HttpResponse {
        HttpResponse::build(self.status_code()).body(self.to_string())
    }
}

pub type HttpResult = Result<HttpResponse, HttpFailure>;
