use axum::{extract::State, Json};
use common_contracts::config_models::{AnalysisTemplateSets, DataSourcesConfig, LlmProvidersConfig};
use service_kit::api;
use crate::{db::system_config, AppState, ServerError};

#[api(GET, "/api/v1/configs/llm_providers", output(detail = "LlmProvidersConfig"))]
pub async fn get_llm_providers_config(
    State(state): State<AppState>,
) -> Result<Json<LlmProvidersConfig>, ServerError> {
    let pool = state.pool();
    let config = system_config::get_config::<LlmProvidersConfig>(pool, "llm_providers").await?;
    Ok(Json(config))
}

#[api(PUT, "/api/v1/configs/llm_providers", output(detail = "LlmProvidersConfig"))]
pub async fn update_llm_providers_config(
    State(state): State<AppState>,
    Json(payload): Json<LlmProvidersConfig>,
) -> Result<Json<LlmProvidersConfig>, ServerError> {
    let pool = state.pool();
    let updated_config = system_config::update_config(pool, "llm_providers", &payload).await?;
    Ok(Json(updated_config))
}

#[api(GET, "/api/v1/configs/analysis_template_sets", output(detail = "AnalysisTemplateSets"))]
pub async fn get_analysis_template_sets(
    State(state): State<AppState>,
) -> Result<Json<AnalysisTemplateSets>, ServerError> {
    let pool = state.pool();
    let config = system_config::get_config::<AnalysisTemplateSets>(pool, "analysis_template_sets").await?;
    Ok(Json(config))
}

#[api(PUT, "/api/v1/configs/analysis_template_sets", output(detail = "AnalysisTemplateSets"))]
pub async fn update_analysis_template_sets(
    State(state): State<AppState>,
    Json(payload): Json<AnalysisTemplateSets>,
) -> Result<Json<AnalysisTemplateSets>, ServerError> {
    let pool = state.pool();
    let updated = system_config::update_config(pool, "analysis_template_sets", &payload).await?;
    Ok(Json(updated))
}

#[api(
    GET,
    "/api/v1/configs/data_sources",
    output(detail = "DataSourcesConfig")
)]
pub async fn get_data_sources_config(
    State(state): State<AppState>,
) -> Result<Json<DataSourcesConfig>, ServerError> {
    let pool = state.pool();
    let config = system_config::get_config::<DataSourcesConfig>(pool, "data_sources").await?;
    Ok(Json(config))
}

#[api(
    PUT,
    "/api/v1/configs/data_sources",
    output(detail = "DataSourcesConfig")
)]
pub async fn update_data_sources_config(
    State(state): State<AppState>,
    Json(payload): Json<DataSourcesConfig>,
) -> Result<Json<DataSourcesConfig>, ServerError> {
    let pool = state.pool();
    let updated_config = system_config::update_config(pool, "data_sources", &payload).await?;
    Ok(Json(updated_config))
}
