use common::mmap;
use common::universal_io::{IsNotFound, UniversalIoError};

use crate::tracker::{PageId, PointOffset};

#[derive(thiserror::Error, Debug)]
pub enum GridstoreError {
    #[error("{0}")]
    Mmap(#[from] mmap::Error),
    #[error("{0}")]
    Io(#[from] std::io::Error),
    #[error("{0}")]
    UniversalIo(#[from] UniversalIoError),
    #[error("{0}")]
    SerdeJson(#[from] serde_json::error::Error),
    #[error("Service error: {description}")]
    ServiceError { description: String },
    #[error("Flush was cancelled")]
    FlushCancelled,
    #[error("Validation error: {message}")]
    ValidationError { message: String },
    #[error("Page {page_id} not found")]
    PageNotFound { page_id: PageId },
    #[error("value {point_offset} not found")]
    ValueNotFound { point_offset: PointOffset },
}

impl GridstoreError {
    pub fn service_error(description: impl Into<String>) -> Self {
        GridstoreError::ServiceError {
            description: description.into(),
        }
    }

    pub fn validation_error(message: impl Into<String>) -> Self {
        GridstoreError::ValidationError {
            message: message.into(),
        }
    }
}

impl IsNotFound for GridstoreError {
    fn is_not_found(&self) -> bool {
        match self {
            GridstoreError::UniversalIo(err) => err.is_not_found(),
            GridstoreError::Io(err) => err.is_not_found(),
            GridstoreError::Mmap(err) => err.is_not_found(),
            GridstoreError::SerdeJson(_)
            | GridstoreError::ServiceError { .. }
            | GridstoreError::FlushCancelled
            | GridstoreError::ValidationError { .. }
            | GridstoreError::PageNotFound { .. }
            | GridstoreError::ValueNotFound { .. } => false,
        }
    }
}
