use safer_ffi::prelude::*;
use serde::ser::Serialize;

use crate::{error::DittoError, utils::zstr::ZString};

/// DQL query statement
#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[deprecated = "Use `QueryV2` instead"]
#[doc(hidden)]
pub struct Query {
    pub(crate) inner_string: ZString,
}

#[allow(deprecated)]
impl TryFrom<&str> for Query {
    type Error = DittoError;
    fn try_from(query: &str) -> Result<Query, DittoError> {
        Self::try_from(query.to_string())
    }
}

#[allow(deprecated)]
impl TryFrom<String> for Query {
    type Error = DittoError;
    fn try_from(query: String) -> Result<Query, Self::Error> {
        // TODO(Ronan) Add check of the query when the ffi will offer such method.
        Ok(Self::new(query))
    }
}

#[allow(deprecated)]
impl Query {
    /// Inner constructor to  prepare the string for the FFI.
    fn new(query_str: String) -> Self {
        Self {
            inner_string: char_p::new(query_str).into(),
        }
    }

    /// Prepare Query for FFI layer
    pub(crate) fn prepare_ffi(&self) -> char_p::Ref<'_> {
        (&*self.inner_string).into()
    }
}

/// Arguments that can be used with an associated [`Query`].
/// Currently QueryArguments can only be created from types that implement
/// [`serde::Serialize`].
#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[deprecated = "Use `QueryV2` instead"]
#[doc(hidden)]
pub struct QueryArguments {
    cbor: Vec<u8>,
}

#[allow(deprecated)]
impl<T: Serialize> From<T> for QueryArguments {
    // (Ronan) It would be nice to only accept key-value data but it doesn't seem doable easily
    // with Serde.
    fn from(query_args: T) -> QueryArguments {
        // Unwrap should be safe because the provided input is Serialize.
        let cbor = serde_cbor::to_vec(&query_args).unwrap();
        Self { cbor }
    }
}

#[allow(deprecated)]
impl QueryArguments {
    pub(crate) fn cbor(&self) -> &[u8] {
        &self.cbor
    }
}
