use crate::AppService;
use crate::ai::types::AiDiscussionResponse;
use crate::error::AppError;
use crate::{Pagination, session_user};
use db::sqlx;
use model::ai::AiModelDiscussionModel;
use session::Session;

impl AppService {
    pub async fn ai_model_discussions(
        &self,
        ctx: &Session,
        model_id: uuid::Uuid,
        pagination: Pagination,
    ) -> Result<Vec<AiDiscussionResponse>, AppError> {
        let _user_uid = session_user(ctx)?;

        let discussions = sqlx::query_as::<_, AiModelDiscussionModel>(
            "SELECT id, model, \"user\", parent, body, created_at, updated_at, deleted_at \
             FROM ai_model_discussion WHERE model = $1 AND deleted_at IS NULL \
             ORDER BY created_at DESC LIMIT $2 OFFSET $3",
        )
        .bind(model_id)
        .bind(pagination.limit() as i64)
        .bind(pagination.offset() as i64)
        .fetch_all(self.db.reader())
        .await
        .map_err(|e| AppError::DatabaseError(e.to_string()))?;

        let mut results = Vec::new();
        for d in discussions {
            let user = self.users_find_by_id(d.user).await?;
            results.push(AiDiscussionResponse {
                id: d.id,
                author: crate::issues::types::issue_author(user),
                parent: d.parent,
                body: d.body,
                created_at: d.created_at,
                updated_at: d.updated_at,
            });
        }
        Ok(results)
    }
}
