use crate::{ApiResponse, error::ApiError};
use actix_web::{HttpResponse, Result, web};
use service::AppService;
use service::project::repo::{
    ProjectRepoCreateParams, ProjectRepoCreateResponse, ProjectRepositoryQuery,
};
use session::Session;

#[utoipa::path(
    get,
    path = "/api/projects/{project_name}/repos",
    params(("project_name" = String, Path)),
    responses(
        (status = 200, description = "Get project repositories", body = ApiResponse<service::project::repo::ProjectRepositoryPagination>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Project not found"),
    ),
    tag = "Project"
)]
pub async fn project_repos(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<String>,
    query: web::Query<ProjectRepositoryQuery>,
) -> Result<HttpResponse, ApiError> {
    let project_name = path.into_inner();
    let resp = service
        .project_repo(&session, project_name, query.into_inner())
        .await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    post,
    path = "/api/projects/{project_name}/repos",
    params(("project_name" = String, Path)),
    request_body = ProjectRepoCreateParams,
    responses(
        (status = 200, description = "Create a repository", body = ApiResponse<ProjectRepoCreateResponse>),
        (status = 400, description = "Bad request"),
        (status = 401, description = "Unauthorized"),
        (status = 409, description = "Repository name already exists"),
    ),
    tag = "Project"
)]
pub async fn project_repo_create(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<String>,
    body: web::Json<ProjectRepoCreateParams>,
) -> Result<HttpResponse, ApiError> {
    let project_name = path.into_inner();
    let resp = service
        .project_repo_create(&session, project_name, body.into_inner())
        .await?;
    Ok(ApiResponse::ok(resp).to_response())
}
