//! Provider management — delegates to agent crate.

use crate::AppService;
use crate::error::AppError;
use session::Session;
use uuid::Uuid;

pub use agent::model::provider::{CreateProviderRequest, ProviderResponse, UpdateProviderRequest};

pub(crate) fn require_system_caller(ctx: &Session) -> Result<(), AppError> {
    if ctx.user() != Some(Uuid::nil()) {
        return Err(AppError::Unauthorized);
    }
    Ok(())
}

impl AppService {
    pub async fn agent_provider_list(
        &self,
        _ctx: &Session,
    ) -> Result<Vec<agent::model::provider::ProviderResponse>, AppError> {
        Ok(agent::model::provider::list_providers(&self.db).await?)
    }

    pub async fn agent_provider_get(
        &self,
        id: Uuid,
        _ctx: &Session,
    ) -> Result<agent::model::provider::ProviderResponse, AppError> {
        Ok(agent::model::provider::get_provider(&self.db, id).await?)
    }

    pub async fn agent_provider_create(
        &self,
        request: agent::model::provider::CreateProviderRequest,
        ctx: &Session,
    ) -> Result<agent::model::provider::ProviderResponse, AppError> {
        require_system_caller(ctx)?;
        Ok(agent::model::provider::create_provider(&self.db, request).await?)
    }

    pub async fn agent_provider_update(
        &self,
        id: Uuid,
        request: agent::model::provider::UpdateProviderRequest,
        ctx: &Session,
    ) -> Result<agent::model::provider::ProviderResponse, AppError> {
        require_system_caller(ctx)?;
        Ok(agent::model::provider::update_provider(&self.db, id, request).await?)
    }

    pub async fn agent_provider_delete(
        &self,
        id: Uuid,
        ctx: &Session,
    ) -> Result<(), AppError> {
        require_system_caller(ctx)?;
        Ok(agent::model::provider::delete_provider(&self.db, id).await?)
    }
}
