use crate::error::ApiError;
use crate::{ApiResponse, api_success};
use actix_web::{HttpResponse, Result, web};
use service::AppService;
use service::git::branch_protection::{
    ApprovalCheckResult, BranchProtectionCreateRequest, BranchProtectionResponse,
    BranchProtectionUpdateRequest,
};
use session::Session;

#[derive(serde::Deserialize, utoipa::IntoParams)]
pub struct ProtectionCheckQuery {
    pub pr_number: i64,
}

#[utoipa::path(
    get,
    path = "/api/repos/{namespace}/{repo}/branch-protections",
    params(
        ("namespace" = String, Path, description = "Project namespace"),
        ("repo" = String, Path, description = "Repository name"),
    ),
    responses(
        (status = 401, description = "Unauthorized", body = ApiResponse<ApiError>),
        (status = 200, description = "List branch protection rules", body = ApiResponse<Vec<BranchProtectionResponse>>),
    ),
    tag = "Git"
)]
pub async fn branch_protection_list(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(String, String)>,
) -> Result<HttpResponse, ApiError> {
    let (namespace, repo) = path.into_inner();
    let rules = service
        .branch_protection_list(namespace, repo, &session)
        .await?;
    Ok(ApiResponse::ok(rules).to_response())
}

#[utoipa::path(
    get,
    path = "/api/repos/{namespace}/{repo}/branch-protections/{id}",
    params(
        ("namespace" = String, Path, description = "Project namespace"),
        ("repo" = String, Path, description = "Repository name"),
        ("id" = i64, Path, description = "Rule id"),
    ),
    responses(
        (status = 401, description = "Unauthorized", body = ApiResponse<ApiError>),
        (status = 200, description = "Get a branch protection rule", body = ApiResponse<BranchProtectionResponse>),
        (status = 404, description = "Not found", body = ApiResponse<ApiError>),
    ),
    tag = "Git"
)]
pub async fn branch_protection_get(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(String, String, i64)>,
) -> Result<HttpResponse, ApiError> {
    let (namespace, repo, id) = path.into_inner();
    let rule = service
        .branch_protection_get(namespace, repo, id, &session)
        .await?;
    Ok(ApiResponse::ok(rule).to_response())
}

#[utoipa::path(
    post,
    path = "/api/repos/{namespace}/{repo}/branch-protections",
    params(
        ("namespace" = String, Path, description = "Project namespace"),
        ("repo" = String, Path, description = "Repository name"),
    ),
    request_body = BranchProtectionCreateRequest,
    responses(
        (status = 401, description = "Unauthorized", body = ApiResponse<ApiError>),
        (status = 200, description = "Create a branch protection rule", body = ApiResponse<BranchProtectionResponse>),
    ),
    tag = "Git"
)]
pub async fn branch_protection_create(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(String, String)>,
    body: web::Json<BranchProtectionCreateRequest>,
) -> Result<HttpResponse, ApiError> {
    let (namespace, repo) = path.into_inner();
    let rule = service
        .branch_protection_create(namespace, repo, body.into_inner(), &session)
        .await?;
    Ok(ApiResponse::ok(rule).to_response())
}

#[utoipa::path(
    patch,
    path = "/api/repos/{namespace}/{repo}/branch-protections/{id}",
    params(
        ("namespace" = String, Path, description = "Project namespace"),
        ("repo" = String, Path, description = "Repository name"),
        ("id" = i64, Path, description = "Rule id"),
    ),
    request_body = BranchProtectionUpdateRequest,
    responses(
        (status = 401, description = "Unauthorized", body = ApiResponse<ApiError>),
        (status = 200, description = "Update a branch protection rule", body = ApiResponse<BranchProtectionResponse>),
        (status = 404, description = "Not found", body = ApiResponse<ApiError>),
    ),
    tag = "Git"
)]
pub async fn branch_protection_update(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(String, String, i64)>,
    body: web::Json<BranchProtectionUpdateRequest>,
) -> Result<HttpResponse, ApiError> {
    let (namespace, repo, id) = path.into_inner();
    let rule = service
        .branch_protection_update(namespace, repo, id, body.into_inner(), &session)
        .await?;
    Ok(ApiResponse::ok(rule).to_response())
}

#[utoipa::path(
    delete,
    path = "/api/repos/{namespace}/{repo}/branch-protections/{id}",
    params(
        ("namespace" = String, Path, description = "Project namespace"),
        ("repo" = String, Path, description = "Repository name"),
        ("id" = i64, Path, description = "Rule id"),
    ),
    responses(
        (status = 401, description = "Unauthorized", body = ApiResponse<ApiError>),
        (status = 200, description = "Delete a branch protection rule"),
        (status = 404, description = "Not found", body = ApiResponse<ApiError>),
    ),
    tag = "Git"
)]
pub async fn branch_protection_delete(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(String, String, i64)>,
) -> Result<HttpResponse, ApiError> {
    let (namespace, repo, id) = path.into_inner();
    service
        .branch_protection_delete(namespace, repo, id, &session)
        .await?;
    Ok(api_success())
}

#[utoipa::path(
    get,
    path = "/api/repos/{namespace}/{repo}/branch-protections/check-approvals",
    params(
        ("namespace" = String, Path, description = "Project namespace"),
        ("repo" = String, Path, description = "Repository name"),
        ("pr_number" = i64, Query, description = "Pull request number"),
    ),
    responses(
        (status = 401, description = "Unauthorized", body = ApiResponse<ApiError>),
        (status = 200, description = "Check approval count against branch protection", body = ApiResponse<ApprovalCheckResult>),
        (status = 404, description = "Not found", body = ApiResponse<ApiError>),
    ),
    tag = "Git"
)]
pub async fn branch_protection_check_approvals(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(String, String)>,
    query: web::Query<ProtectionCheckQuery>,
) -> Result<HttpResponse, ApiError> {
    let (namespace, repo) = path.into_inner();
    let result = service
        .branch_protection_check_approvals(namespace, repo, query.pr_number, &session)
        .await?;
    Ok(ApiResponse::ok(result).to_response())
}
