use thiserror::Error;

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

#[derive(Debug, Error)]
pub enum Error {
    #[error("storage error: {0}")]
    Storage(String),

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

    #[error("mls protocol error: {0}")]
    Mls(String),

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

    #[error("unknown conversation: {0}")]
    UnknownConversation(String),

    #[error("unknown device: {0}")]
    UnknownDevice(String),

    #[error("epoch occupied: caller must rebase on the new epoch and retry")]
    EpochOccupied,

    /// The KeyPackage (or its private init key) needed to join is gone — it was
    /// already consumed (single-use reuse) or the recipient's pool is exhausted.
    /// Host action: top up KeyPackages (publish a last-resort KP) and have the
    /// inviter retry. Distinct from a generic `Mls` error so the host can react
    /// instead of treating every join failure the same.
    #[error("key package not found: already consumed or pool exhausted")]
    KeyPackageNotFound,

    /// This conversation is behind the group's current epoch and can no longer
    /// decrypt newer traffic from local state alone — a Commit was missed (the
    /// device was offline across a rekey, or a Commit was dropped). Host action:
    /// recover via re-Welcome or a same-user state snapshot. Carries the
    /// conversation id (hex) so the host knows which chat to repair.
    #[error("conversation stranded behind epoch (missed commit), needs recovery: {0}")]
    EpochStranded(String),

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

    #[error("invalid input: {0}")]
    Invalid(String),

    #[error("not initialised")]
    NotInitialised,
}

impl Error {
    pub(crate) fn mls<E: std::fmt::Display>(e: E) -> Self {
        Error::Mls(e.to_string())
    }
    pub(crate) fn codec<E: std::fmt::Display>(e: E) -> Self {
        Error::Codec(e.to_string())
    }
}
