use std::fmt::Display;

use serde::Serialize;

use crate::utils::ApplicationError;

#[derive(sqlx::Type, Debug, Clone, Copy, PartialEq, Eq, Serialize, PartialOrd, Ord)]
#[sqlx(type_name = "function", rename_all = "lowercase")]
pub enum Function {
    Posten = 1,
    Fuehrungsassistent = 5,
    Wachhabender = 10,
}

impl Display for Function {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Function::Posten => write!(f, "Posten"),
            Function::Fuehrungsassistent => write!(f, "Führungsassistent"),
            Function::Wachhabender => write!(f, "Wachhabender"),
        }
    }
}

impl TryFrom<u8> for Function {
    type Error = ApplicationError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            1 => Ok(Function::Posten),
            10 => Ok(Function::Wachhabender),
            _ => Err(ApplicationError::UnsupportedEnumValue {
                value: value.to_string(),
                enum_name: String::from("Function"),
            }),
        }
    }
}

impl Default for Function {
    fn default() -> Self {
        Self::Posten
    }
}
