use actix_web::{HttpResponse, web};
use serde::{Deserialize, Serialize};
use service::{
    AppService,
    git::init::{CloneRepo, CreateRepo},
};
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 WkPath {
    pub wk: String,
}
#[utoipa::path(
    post, path = "/api/v1/workspace/{wk}/repos",
    params(("wk" = String, Path, description = "Workspace name")),
    request_body = CreateRepo,
    responses((status = 200, description = "Repo created"), (status = 401, description = "Unauthorized"),
        (status = 403, description = "Permission denied"), (status = 409, description = "Repo name exists")),
    security(("session" = []))
)]
pub async fn create_repo(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<WkPath>,
    params: web::Json<CreateRepo>,
) -> Result<HttpResponse, ApiError> {
    let wk = path.into_inner().wk;
    let data = service
        .git_init_bare(&session, &wk, params.into_inner())
        .await?;
    ok_json(data)
}

#[utoipa::path(
    post, path = "/api/v1/workspace/{wk}/repos/clone",
    params(("wk" = String, Path, description = "Workspace name")),
    request_body = CloneRepo,
    responses((status = 200, description = "Repo cloned"), (status = 401, description = "Unauthorized"),
        (status = 403, description = "Permission denied"), (status = 409, description = "Repo name exists")),
    security(("session" = []))
)]
pub async fn clone_repo(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<WkPath>,
    params: web::Json<CloneRepo>,
) -> Result<HttpResponse, ApiError> {
    let wk = path.into_inner().wk;
    let data = service
        .git_clone_bare(&session, &wk, params.into_inner())
        .await?;
    ok_json(data)
}
