use crate::AppService;
use crate::ai::types::AiModelVersionResponse;
use crate::error::AppError;
use db::sqlx;
use model::ai::AiModelVersionModel;
use session::Session;

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

        self.ai_version_list_inner(model_id).await
    }

    pub async fn ai_version_list_inner(
        &self,
        model_id: uuid::Uuid,
    ) -> Result<Vec<AiModelVersionResponse>, AppError> {
        let versions = sqlx::query_as::<_, AiModelVersionModel>(
            "SELECT id, model, version, provider_model_name, \
             input_price_per_million, output_price_per_million, cached_input_price_per_million, \
             training_cutoff, released_at, deprecated_at, enabled, created_at, updated_at \
             FROM ai_model_version WHERE model = $1 AND enabled = true \
             ORDER BY released_at DESC",
        )
        .bind(model_id)
        .fetch_all(self.db.reader())
        .await
        .map_err(|e| AppError::DatabaseError(e.to_string()))?;

        Ok(versions
            .into_iter()
            .map(AiModelVersionResponse::from)
            .collect())
    }
}
