use actix_web::{HttpResponse, web};
use serde::Serialize;
use service::{
    AppService, Pagination,
    git::fork::{CreateFork, ForkResponse},
};
use session::Session;

use crate::error::ApiError;

use super::repo::WkRepoPath;

fn ok_json<T: Serialize>(data: T) -> Result<HttpResponse, ApiError> {
    Ok(HttpResponse::Ok().json(data))
}
#[utoipa::path(
    post,
    path = "/api/v1/workspace/{wk}/repos/{repo}/forks",
    params(WkRepoPath),
    request_body = CreateFork,
    responses(
        (status = 200, body = ForkResponse),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Cannot fork private repo"),
        (status = 409, description = "Fork already exists"),
    ),
    security(("session" = []))
)]
pub async fn create_fork(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<WkRepoPath>,
    params: web::Json<CreateFork>,
) -> Result<HttpResponse, ApiError> {
    let WkRepoPath { wk, repo } = path.into_inner();
    let data = service
        .repo_fork_create(&session, &wk, &repo, params.into_inner())
        .await?;
    ok_json(data)
}
#[utoipa::path(
    get,
    path = "/api/v1/workspace/{wk}/repos/{repo}/forks",
    params(WkRepoPath, Pagination),
    responses(
        (status = 200, body = Vec<ForkResponse>),
        (status = 401, description = "Unauthorized"),
    ),
    security(("session" = []))
)]
pub async fn list_forks(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<WkRepoPath>,
    pagination: web::Query<Pagination>,
) -> Result<HttpResponse, ApiError> {
    let WkRepoPath { wk, repo } = path.into_inner();
    let data = service
        .repo_fork_list(&session, &wk, &repo, pagination.into_inner())
        .await?;
    ok_json(data)
}
