use actix_web::{HttpResponse, web};
use serde::{Deserialize, Serialize};
use service::AppService;
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 ArchiveQuery {
    #[serde(default = "default_format")]
    pub format: String,
    pub tree: Option<String>,
    pub prefix: Option<String>,
    pub pathspec: Option<Vec<String>>,
}

fn default_format() -> String {
    "tar".to_string()
}
#[utoipa::path(
    get, path = "/api/v1/workspace/{wk}/repos/{repo}/git/archive",
    params(WkRepoPath, ArchiveQuery),
    responses((status = 200, description = "Archive download")),
    security(("session" = []))
)]
pub async fn archive(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<WkRepoPath>,
    query: web::Query<ArchiveQuery>,
) -> Result<HttpResponse, ApiError> {
    let WkRepoPath { wk, repo } = path.into_inner();
    match query.format.as_str() {
        "zip" => {
            ok_json(service.git_archive_zip(&session, &wk, &repo, None).await?)
        }
        _ => {
            ok_json(service.git_archive_tar(&session, &wk, &repo, None).await?)
        }
    }
}
