use crate::AppService;
use crate::ai::types::AiProviderResponse;
use crate::error::AppError;
use db::sqlx;
use model::ai::AiProviderModel;
use session::Session;

impl AppService {
    pub async fn ai_provider_list(
        &self,
        ctx: &Session,
    ) -> Result<Vec<AiProviderResponse>, AppError> {
        self.ai_require_login(ctx).await?;

        let providers = sqlx::query_as::<_, AiProviderModel>(
            "SELECT id, name, base_url, website_url, logo_url, enabled, created_at, updated_at \
             FROM ai_provider WHERE enabled = true ORDER BY name ASC",
        )
        .fetch_all(self.db.reader())
        .await
        .map_err(|e| AppError::DatabaseError(e.to_string()))?;

        Ok(providers
            .into_iter()
            .map(AiProviderResponse::from)
            .collect())
    }
    pub async fn ai_provider_get(
        &self,
        ctx: &Session,
        id: uuid::Uuid,
    ) -> Result<AiProviderResponse, AppError> {
        self.ai_require_login(ctx).await?;

        let provider = sqlx::query_as::<_, AiProviderModel>(
            "SELECT id, name, base_url, website_url, logo_url, enabled, created_at, updated_at \
             FROM ai_provider WHERE id = $1",
        )
        .bind(id)
        .fetch_optional(self.db.reader())
        .await
        .map_err(|e| AppError::DatabaseError(e.to_string()))?
        .ok_or(AppError::NotFound("provider not found".to_string()))?;

        Ok(AiProviderResponse::from(provider))
    }
}
