//! # API controller

use actix_web::HttpResponse;
use actix_web::body::BoxBody;
use std::fmt::{Debug, Display, Formatter};
use zip::result::ZipError;

pub mod accommodations_list_controller;
pub mod accommodations_reservations_calendars_controller;
pub mod accommodations_reservations_controller;
pub mod auth_controller;
pub mod couples_controller;
pub mod data_controller;
pub mod families_controller;
pub mod members_controller;
pub mod photos_controller;
pub mod server_controller;
pub mod users_controller;

/// Custom error to ease controller writing
#[derive(Debug)]
pub struct HttpErr {
    err: anyhow::Error,
}

impl Display for HttpErr {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&self.err, f)
    }
}

impl actix_web::error::ResponseError for HttpErr {
    fn error_response(&self) -> HttpResponse<BoxBody> {
        log::error!("Error while processing request! {self}");
        HttpResponse::InternalServerError().body("Failed to execute request!")
    }
}

impl From<anyhow::Error> for HttpErr {
    fn from(err: anyhow::Error) -> HttpErr {
        HttpErr { err }
    }
}

impl From<ZipError> for HttpErr {
    fn from(value: ZipError) -> Self {
        HttpErr { err: value.into() }
    }
}

impl From<serde_json::Error> for HttpErr {
    fn from(value: serde_json::Error) -> Self {
        HttpErr { err: value.into() }
    }
}

impl From<std::io::Error> for HttpErr {
    fn from(value: std::io::Error) -> Self {
        HttpErr { err: value.into() }
    }
}

impl From<std::num::ParseIntError> for HttpErr {
    fn from(value: std::num::ParseIntError) -> Self {
        HttpErr { err: value.into() }
    }
}

pub type HttpResult = Result<HttpResponse, HttpErr>;
