use actix_web::{HttpResponse, web};
use serde::{Deserialize, Serialize};
use service::{
    AppService, issues::types::IssueAuthor,
    pull_request::assignee::AssignPrUser,
};
use session::Session;

use crate::error::ApiError;

fn ok_json<T: Serialize>(data: T) -> Result<HttpResponse, ApiError> {
    Ok(HttpResponse::Ok().json(data))
}

#[derive(Deserialize, utoipa::IntoParams)]
pub struct PrPath {
    pub wk: String,
    pub repo: String,
    pub number: i64,
}

#[derive(Deserialize, utoipa::IntoParams)]
pub struct UnassignQuery {
    pub username: String,
}
#[utoipa::path(
    post,
    path = "/api/v1/workspace/{wk}/repos/{repo}/pull-requests/{number}/assignees",
    params(PrPath),
    request_body = AssignPrUser,
    responses(
        (status = 200, body = Vec<IssueAuthor>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "PR not found"),
    ),
    security(("session" = []))
)]
pub async fn assign_user(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<PrPath>,
    params: web::Json<AssignPrUser>,
) -> Result<HttpResponse, ApiError> {
    let PrPath { wk, repo, number } = path.into_inner();
    let data = service
        .pr_assign(&session, &wk, &repo, number, params.into_inner())
        .await?;
    ok_json(data)
}
#[utoipa::path(
    delete,
    path = "/api/v1/workspace/{wk}/repos/{repo}/pull-requests/{number}/assignees",
    params(PrPath),
    responses(
        (status = 200, body = Vec<IssueAuthor>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "PR not found"),
    ),
    security(("session" = []))
)]
pub async fn unassign_user(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<PrPath>,
    query: web::Query<UnassignQuery>,
) -> Result<HttpResponse, ApiError> {
    let PrPath { wk, repo, number } = path.into_inner();
    let data = service
        .pr_unassign(&session, &wk, &repo, number, &query.username)
        .await?;
    ok_json(data)
}
