use core::fmt;

#[derive(Debug, Clone)]
pub struct Error {
  status: u16,
  details: String,
}

impl Error {
  pub fn new(status: u16, details: String) -> Self {
    Self { status, details }
  }

  pub fn status(&self) -> u16 {
    self.status
  }

  pub fn details(&self) -> &str {
    &self.details
  }
}

impl fmt::Display for Error {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "{}", self.details)
  }
}

impl std::error::Error for Error {
  fn description(&self) -> &str {
    &self.details
  }
}

impl From<oauth2::url::ParseError> for Error {
  fn from(error: oauth2::url::ParseError) -> Self {
    Self::new(500, error.to_string())
  }
}

impl From<jsonwebtoken::errors::Error> for Error {
  fn from(error: jsonwebtoken::errors::Error) -> Self {
    Self::new(500, error.to_string())
  }
}

impl From<reqwest::Error> for Error {
  fn from(error: reqwest::Error) -> Self {
    let status = error
      .status()
      .unwrap_or(reqwest::StatusCode::INTERNAL_SERVER_ERROR);
    Self::new(status.as_u16(), error.to_string())
  }
}
