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}/subscribers",
    params(
        ("project" = String, Path),
        ("number" = i64, Path),
    ),
    responses(
        (status = 200, description = "List issue subscribers", body = ApiResponse<Vec<service::issue::IssueSubscriberResponse>>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Not found"),
),
    tag = "Issues"
)]
pub async fn issue_subscriber_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_subscriber_list(project, issue_number, &session)
        .await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    post,
    path = "/api/issue/{project}/issues/{number}/subscribe",
    params(
        ("project" = String, Path),
        ("number" = i64, Path),
    ),
    responses(
        (status = 200, description = "Subscribe to issue", body = ApiResponse<service::issue::IssueSubscriberResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Forbidden"),
        (status = 404, description = "Not found"),
),
    tag = "Issues"
)]
pub async fn issue_subscribe(
    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_subscribe(project, issue_number, &session)
        .await?;
    Ok(ApiResponse::ok(resp).to_response())
}

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