use actix_web::{HttpResponse, web};
use serde::Serialize;
use service::{
    AppService,
    user::chpc::{ContributionHeatmapQuery, ContributionHeatmapResponse},
};
use session::Session;

use crate::error::ApiError;

fn ok_json<T: Serialize>(data: T) -> Result<HttpResponse, ApiError> {
    Ok(HttpResponse::Ok().json(data))
}

fn ok() -> Result<HttpResponse, ApiError> {
    Ok(HttpResponse::Ok().finish())
}

#[utoipa::path(
    get,
    path = "/api/v1/user/contribution-heatmap",
    params(
        ContributionHeatmapQuery
    ),
    responses(
        (status = 200, body = ContributionHeatmapResponse)
    ),
    tag = "user"
)]
pub async fn contribution_heatmap(
    service: web::Data<AppService>,
    session: Session,
    query: web::Query<ContributionHeatmapQuery>,
) -> Result<HttpResponse, ApiError> {
    let response = service.user_chpc(&session, query.into_inner()).await?;
    ok_json(response)
}

#[utoipa::path(
    delete,
    path = "/api/v1/user/contribution-heatmap/cache",
    responses(
        (status = 200)
    ),
    tag = "user"
)]
pub async fn invalidate_chpc_cache(
    service: web::Data<AppService>,
    session: Session,
) -> Result<HttpResponse, ApiError> {
    service.user_invalidate_chpc_cache(&session).await?;
    ok()
}
