use context::Context;
use std::{fmt::Display, sync::Arc};

pub type Result<R> = std::result::Result<R, Error>;

pub(crate) struct Error {
    pub ctx: Option<Arc<Context>>,
    pub message: String,
}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.ctx {
            Some(ctx) => write!(f, "[{}] {}", ctx.id(), self.message),
            None => write!(f, "{}", self.message),
        }
    }
}

impl Error {
    pub fn new(message: String) -> Self {
        Error { ctx: None, message }
    }

    pub fn ctx(mut self, ctx: Arc<Context>) -> Self {
        ctx.push_phase("mutex_error", Some(self.message.clone()));
        self.ctx = Some(ctx);
        self
    }
}

impl From<sqlx::error::Error> for Error {
    fn from(err: sqlx::error::Error) -> Self {
        Error::new(err.to_string())
    }
}
