use actix_web::{HttpResponse, web};
use serde::{Deserialize, Serialize};
use service::AppService;
use service::git::refs::GitRefResponse;
use session::Session;

use crate::error::ApiError;

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

#[derive(Deserialize, utoipa::IntoParams)]
pub struct WkRepoPath {
    pub wk: String,
    pub repo: String,
}

#[derive(Deserialize, utoipa::IntoParams)]
pub struct RefQuery {
    pub r#ref: Option<String>,
}

#[utoipa::path(
    get, path = "/api/v1/workspace/{wk}/repos/{repo}/git/refs",
    params(WkRepoPath, RefQuery),
    responses((status = 200, body = Vec<GitRefResponse>)),
    security(("session" = []))
)]
pub async fn list_refs(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<WkRepoPath>,
    query: web::Query<RefQuery>,
) -> Result<HttpResponse, ApiError> {
    if let Some(ref_name) = &query.r#ref {
        let r = service
            .git_ref_get_by_name(&session, &path.wk, &path.repo, ref_name)
            .await?;
        return ok_json(vec![r]);
    }
    ok_json(
        service
            .git_ref_list_by_name(&session, &path.wk, &path.repo)
            .await?,
    )
}
