use crate::AppService;
use crate::ai::types::AiLikeResponse;
use crate::error::AppError;
use db::sqlx;
use model::ai::AiModelLikeModel;
use session::Session;

impl AppService {
    pub async fn ai_model_likes(
        &self,
        ctx: &Session,
        model_id: uuid::Uuid,
    ) -> Result<Vec<AiLikeResponse>, AppError> {
        let _user_uid = self.ai_require_login(ctx).await?;

        let likes = sqlx::query_as::<_, AiModelLikeModel>(
            "SELECT model, \"user\", created_at FROM ai_model_like WHERE model = $1 \
             ORDER BY created_at DESC",
        )
        .bind(model_id)
        .fetch_all(self.db.reader())
        .await
        .map_err(|e| AppError::DatabaseError(e.to_string()))?;

        let mut results = Vec::new();
        for l in likes {
            let user = self.users_find_by_id(l.user).await?;
            results.push(AiLikeResponse {
                user: crate::issues::types::issue_author(user),
                created_at: l.created_at,
            });
        }
        Ok(results)
    }

    pub async fn ai_like_count_inner(
        &self,
        model_id: uuid::Uuid,
    ) -> Result<i64, AppError> {
        let count = sqlx::query_scalar::<_, i64>(
            "SELECT COUNT(*) FROM ai_model_like WHERE model = $1",
        )
        .bind(model_id)
        .fetch_one(self.db.reader())
        .await
        .map_err(|e| AppError::DatabaseError(e.to_string()))?;
        Ok(count)
    }
}
