use crate::{ApiResponse, error::ApiError};
use actix_web::{HttpResponse, Result, web};
use service::AppService;
use session::Session;

#[utoipa::path(
    get,
    path = "/api/issue/{project}/issues/{number}/labels",
    params(
        ("project" = String, Path),
        ("number" = i64, Path),
    ),
    responses(
        (status = 200, description = "List issue labels", body = ApiResponse<Vec<service::issue::IssueLabelResponse>>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Not found"),
),
    tag = "Issues"
)]
pub async fn issue_label_list(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(String, i64)>,
) -> Result<HttpResponse, ApiError> {
    let (project, issue_number) = path.into_inner();
    let resp = service
        .issue_label_list(project, issue_number, &session)
        .await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    post,
    path = "/api/issue/{project}/issues/{number}/labels",
    params(
        ("project" = String, Path),
        ("number" = i64, Path),
    ),
    request_body = service::issue::IssueAddLabelRequest,
    responses(
        (status = 200, description = "Add label to issue", body = ApiResponse<service::issue::IssueLabelResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Forbidden"),
        (status = 404, description = "Not found"),
),
    tag = "Issues"
)]
pub async fn issue_label_add(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(String, i64)>,
    body: web::Json<service::issue::IssueAddLabelRequest>,
) -> Result<HttpResponse, ApiError> {
    let (project, issue_number) = path.into_inner();
    let resp = service
        .issue_label_add(project, issue_number, body.into_inner(), &session)
        .await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    delete,
    path = "/api/issue/{project}/issues/{number}/labels/{label_id}",
    params(
        ("project" = String, Path),
        ("number" = i64, Path),
        ("label_id" = i64, Path),
    ),
    responses(
        (status = 200, description = "Remove label from issue"),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Forbidden"),
        (status = 404, description = "Not found"),
),
    tag = "Issues"
)]
pub async fn issue_label_remove(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(String, i64, i64)>,
) -> Result<HttpResponse, ApiError> {
    let (project, issue_number, label_id) = path.into_inner();
    service
        .issue_label_remove(project, issue_number, label_id, &session)
        .await?;
    Ok(ApiResponse::ok(serde_json::json!({ "success": true })).to_response())
}
