use crate::{
    db,
    AppState, ServerError,
};
use axum::{
    extract::{Query, State},
    Json,
    http::StatusCode,
};
use common_contracts::dtos::ProviderCacheDto;
use service_kit::api;
use anyhow::Error as AnyhowError;
use serde::Deserialize;

#[derive(Deserialize, utoipa::ToSchema)]
pub struct CacheQuery {
    pub key: String,
}

#[api(GET, "/api/v1/provider-cache")]
pub async fn get_cache(
    State(state): State<AppState>,
    Query(query): Query<CacheQuery>,
) -> Result<Json<Option<ProviderCacheDto>>, ServerError> {
    // Detailed logging might be too noisy for cache hits, so keep it simple
    let data = db::get_cache(&state.pool, &query.key).await.map_err(AnyhowError::from)?;
    Ok(Json(data))
}

#[api(POST, "/api/v1/provider-cache")]
pub async fn set_cache(
    State(state): State<AppState>,
    Json(payload): Json<ProviderCacheDto>,
) -> Result<StatusCode, ServerError> {
    db::set_cache(&state.pool, &payload).await.map_err(AnyhowError::from)?;
    Ok(StatusCode::OK)
}

