//! D-Bus error type. Maps `DbError` and `CodecError` onto the
//! `org.liberux.Contacts1.Error.*` namespace described in
//! `docs/dbus-api.md`.

use crate::db::DbError;
use crate::model::data_fields::CodecError;

/// Errors returned by every method on `org.liberux.Contacts1`.
///
/// The `#[ zbus( error ) ]` variant captures internal zbus errors and is
/// re-emitted on the wire under whichever name zbus uses (typically the
/// `org.freedesktop.DBus.Error.*` family); the others map 1:1 to error
/// names in the `org.liberux.Contacts1.Error` family.
#[ derive( Debug, zbus::DBusError ) ]
#[ zbus( prefix = "org.liberux.Contacts1.Error" ) ]
pub enum Error
{
	#[ zbus( error ) ]
	ZBus( zbus::Error ),

	NotFound( String ),
	InvalidArgument( String ),
	Conflict( String ),
	PermissionDenied( String ),
	Internal( String ),
}

impl From<DbError> for Error
{
	fn from( e: DbError ) -> Self
	{
		match e
		{
			DbError::NotFound                  => Error::NotFound( "no such row".into() ),
			DbError::InvalidArgument( msg )    => Error::InvalidArgument( msg ),
			DbError::Sqlite( inner )           => Error::Internal( format!( "sqlite: {inner}" ) ),
		}
	}
}

impl From<CodecError> for Error
{
	fn from( e: CodecError ) -> Self
	{
		Error::InvalidArgument( e.to_string() )
	}
}
