// SPDX-FileCopyrightText: 2025 Simon Brummer
//
// SPDX-License-Identifier: MPL-2.0

use thiserror::Error;

/// Error type expressing configuration loading failures.
#[derive(Error, Debug)]
pub enum LoadError {
    /// An I/O error occurred during configuration file reading.
    #[error(transparent)]
    Io(#[from] std::io::Error),

    /// Data deserialization failed.
    #[error(transparent)]
    Deserialize(#[from] anyhow::Error),
}

/// Error type expressing configuration storing failures.
#[derive(Error, Debug)]
pub enum SaveError {
    /// An I/O error occurred during configuration file writing.
    #[error(transparent)]
    Io(#[from] std::io::Error),

    /// Data serialization failed.
    #[error(transparent)]
    Serialize(#[from] anyhow::Error),
}

#[cfg(feature = "json")]
impl From<serde_json::Error> for LoadError {
    fn from(value: serde_json::Error) -> Self {
        Self::Deserialize(value.into())
    }
}

#[cfg(feature = "json")]
impl From<serde_json::Error> for SaveError {
    fn from(value: serde_json::Error) -> Self {
        Self::Serialize(value.into())
    }
}

#[cfg(feature = "toml")]
impl From<toml::de::Error> for LoadError {
    fn from(value: toml::de::Error) -> Self {
        Self::Deserialize(value.into())
    }
}

#[cfg(feature = "toml")]
impl From<toml::ser::Error> for SaveError {
    fn from(value: toml::ser::Error) -> Self {
        Self::Serialize(value.into())
    }
}

#[cfg(feature = "yaml")]
impl From<serde_saphyr::Error> for LoadError {
    fn from(value: serde_saphyr::Error) -> Self {
        Self::Deserialize(value.into())
    }
}

#[cfg(feature = "yaml")]
impl From<serde_saphyr::ser::Error> for SaveError {
    fn from(value: serde_saphyr::ser::Error) -> Self {
        Self::Serialize(value.into())
    }
}

#[cfg(test)]
pub mod mocks {
    use super::{Error, LoadError, SaveError};

    #[derive(Error, Debug)]
    #[error("Mock Error Type")]
    pub struct MockError;

    impl From<MockError> for LoadError {
        fn from(value: MockError) -> Self {
            Self::Deserialize(value.into())
        }
    }

    impl From<MockError> for SaveError {
        fn from(value: MockError) -> Self {
            Self::Serialize(value.into())
        }
    }
}
