use crate::{
    config::Config,
    error::TupleleapAIError,
    types::{
        AssistantEventStream, AssistantStreamEvent, CreateThreadAndRunRequest, CreateThreadRequest,
        DeleteThreadResponse, ModifyThreadRequest, RunObject, ThreadObject,
    },
    Client, Messages, Runs,
};

/// Create threads that assistants can interact with.
///
/// Related guide: [Assistants](https://platform.TupleleapAI.com/docs/assistants/overview)
pub struct Threads<'c, C: Config> {
    client: &'c Client<C>,
}

impl<'c, C: Config> Threads<'c, C> {
    pub fn new(client: &'c Client<C>) -> Self {
        Self { client }
    }

    /// Call [Messages] group API to manage message in [thread_id] thread.
    pub fn messages(&self, thread_id: &str) -> Messages<C> {
        Messages::new(self.client, thread_id)
    }

    /// Call [Runs] group API to manage runs in [thread_id] thread.
    pub fn runs(&self, thread_id: &str) -> Runs<C> {
        Runs::new(self.client, thread_id)
    }

    /// Create a thread and run it in one request.
    pub async fn create_and_run(
        &self,
        request: CreateThreadAndRunRequest,
    ) -> Result<RunObject, TupleleapAIError> {
        self.client.post("/threads/runs", request).await
    }

    /// Create a thread and run it in one request (streaming).
    pub async fn create_and_run_stream(
        &self,
        mut request: CreateThreadAndRunRequest,
    ) -> Result<AssistantEventStream, TupleleapAIError> {
        if request.stream.is_some() && !request.stream.unwrap() {
            return Err(TupleleapAIError::InvalidArgument(
                "When stream is false, use Threads::create_and_run".into(),
            ));
        }

        request.stream = Some(true);

        Ok(self
            .client
            .post_stream_mapped_raw_events("/threads/runs", request, AssistantStreamEvent::try_from)
            .await)
    }

    /// Create a thread.
    pub async fn create(&self, request: CreateThreadRequest) -> Result<ThreadObject, TupleleapAIError> {
        self.client.post("/threads", request).await
    }

    /// Retrieves a thread.
    pub async fn retrieve(&self, thread_id: &str) -> Result<ThreadObject, TupleleapAIError> {
        self.client.get(&format!("/threads/{thread_id}")).await
    }

    /// Modifies a thread.
    pub async fn update(
        &self,
        thread_id: &str,
        request: ModifyThreadRequest,
    ) -> Result<ThreadObject, TupleleapAIError> {
        self.client
            .post(&format!("/threads/{thread_id}"), request)
            .await
    }

    /// Delete a thread.
    pub async fn delete(&self, thread_id: &str) -> Result<DeleteThreadResponse, TupleleapAIError> {
        self.client.delete(&format!("/threads/{thread_id}")).await
    }
}
