use thiserror::Error;

#[derive(Error, Debug)]
pub enum DbError {
    #[error("Configuration error: {0}")]
    Config(String),

    #[error("Connection error: {0}")]
    Connection(String),

    #[error("Query error: {0}")]
    Query(String),

    #[error("Transaction error: {0}")]
    Transaction(String),

    #[error("Lock error: {0}")]
    Lock(String),

    #[error("SQL injection detected: {0}")]
    SqlInjection(String),

    #[error("Invalid table name: {0}")]
    InvalidTableName(String),

    #[error("Invalid field name: {0}")]
    InvalidFieldName(String),

    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("Parse error: {0}")]
    Parse(String),

    #[error("Pool error: {0}")]
    Pool(String),

    #[error("Timeout error: {0}")]
    Timeout(String),

    #[error("Not found: {0}")]
    NotFound(String),

    #[error("Database not initialized")]
    NotInitialized,

    #[error("Unknown error: {0}")]
    Unknown(String),
}

pub type DbResult<T> = Result<T, DbError>;

impl From<String> for DbError {
    fn from(s: String) -> Self {
        DbError::Unknown(s)
    }
}

impl From<&str> for DbError {
    fn from(s: &str) -> Self {
        DbError::Unknown(s.to_string())
    }
}

impl<T> From<std::sync::PoisonError<T>> for DbError {
    fn from(e: std::sync::PoisonError<T>) -> Self {
        DbError::Lock(e.to_string())
    }
}
