//! Error mapping from `sqlx` errors to [`klieo_core::error::MemoryError`].

use klieo_core::error::MemoryError;

/// PostgreSQL SQLSTATE for `undefined_table` — raised when a query hits the
/// facts table before the first `remember` has provisioned it.
const UNDEFINED_TABLE: &str = "42P01";

pub(crate) fn store_err(e: sqlx::Error) -> MemoryError {
    MemoryError::Store(e.to_string())
}

/// Whether `e` is PostgreSQL's `undefined_table` (42P01). `recall` /
/// `recall_filtered` map this to an empty result and `forget` to `Ok` — the
/// table is created lazily on first `remember`, so a read that races ahead of
/// any write sees "no facts", not a hard error (mirrors the Qdrant backend's
/// missing-collection handling).
pub(crate) fn is_undefined_table(e: &sqlx::Error) -> bool {
    matches!(e, sqlx::Error::Database(db) if db.code().as_deref() == Some(UNDEFINED_TABLE))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn store_err_routes_to_store_variant() {
        let mem = store_err(sqlx::Error::PoolClosed);
        assert!(matches!(mem, MemoryError::Store(_)));
    }

    #[test]
    fn non_database_error_is_not_undefined_table() {
        assert!(!is_undefined_table(&sqlx::Error::PoolClosed));
    }
}
