use actix_web::{HttpResponse, web};
use serde::{Deserialize, Serialize};
use service::{
    AppService,
    issues::{assignee::AssignIssueUser, types::IssueAuthor},
};
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 AssigneePath {
    pub wk: String,
    pub number: i64,
}
#[utoipa::path(
    post,
    path = "/api/v1/workspace/{wk}/issues/{number}/assignees",
    params(AssigneePath),
    request_body = AssignIssueUser,
    responses(
        (status = 200, body = Vec<IssueAuthor>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Issue not found"),
    ),
    security(
        ("session" = [])
    )
)]
pub async fn assign_user(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<AssigneePath>,
    params: web::Json<AssignIssueUser>,
) -> Result<HttpResponse, ApiError> {
    let AssigneePath { wk, number } = path.into_inner();
    let data = service
        .issue_assign(&session, &wk, number, params.into_inner())
        .await?;
    ok_json(data)
}
#[utoipa::path(
    delete,
    path = "/api/v1/workspace/{wk}/issues/{number}/assignees",
    params(AssigneePath),
    responses(
        (status = 200, body = Vec<IssueAuthor>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Issue not found"),
    ),
    security(
        ("session" = [])
    )
)]
pub async fn unassign_user(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<AssigneePath>,
    query: web::Query<UnassignQuery>,
) -> Result<HttpResponse, ApiError> {
    let AssigneePath { wk, number } = path.into_inner();
    let data = service
        .issue_unassign(&session, &wk, number, &query.username)
        .await?;
    ok_json(data)
}

#[derive(Deserialize, utoipa::IntoParams)]
pub struct UnassignQuery {
    pub username: String,
}
