use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
use chrono::ParseError;
use leptos::ServerFnError;

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum AppError {
    HourParseError,
    ServerError(String),
    FatalError(String),
    SlotParseError,
    MailAddrParseErr(String),
    MailSendError(String)
}

impl AppError {
    fn as_string(&self) -> String {
        match self {
            AppError::HourParseError => {"Hour parse error".to_string()},
            AppError::ServerError(e) => {format!("Server error: {}", e)},
            AppError::FatalError(e) => {format!("Fatal error: {}", e)},
            AppError::SlotParseError => {"Book slot parse error".to_string()},
            AppError::MailAddrParseErr(e) => {format!("Cannot parse email address: {}", e)},
            AppError::MailSendError(e) => {format!("Cannot send email: {}", e)}
        }
    }
}

impl Display for AppError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_string())
    }
}

impl Error for AppError {}

impl From<ServerFnError> for AppError {
    fn from(value: ServerFnError) -> Self {
        AppError::ServerError(value.to_string())
    }
}

#[cfg(feature = "ssr")]
impl From<sqlx::Error> for AppError {
    fn from(value: sqlx::Error) -> Self {
        AppError::FatalError(value.to_string())
    }
}

impl From<ParseError> for AppError {
    fn from(_value: ParseError) -> Self {
        AppError::HourParseError
    }
}

#[cfg(feature = "ssr")]
impl From<lettre::address::AddressError> for AppError {
    fn from(value: lettre::address::AddressError) -> Self {
        AppError::MailAddrParseErr(value.to_string())
    }
}

#[cfg(feature = "ssr")]
impl From<lettre::error::Error> for AppError {
    fn from(value: lettre::error::Error) -> Self {
        AppError::MailSendError(value.to_string())
    }
}

#[cfg(feature = "ssr")]
impl From<lettre::transport::smtp::Error> for AppError {
    fn from(value: lettre::transport::smtp::Error) -> Self {
        AppError::MailSendError(value.to_string())
    }
}

#[cfg(feature = "ssr")]
impl From<lettre::transport::file::Error> for AppError {
    fn from(value: lettre::transport::file::Error) -> Self {
        AppError::MailSendError(value.to_string())
    }
}