use actix_web::{HttpResponse, web};
use serde::{Deserialize, Serialize};
use service::{
    AppService, issues::types::LabelResponse, pull_request::label::AddPrLabel,
};
use session::Session;
use uuid::Uuid;

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 RemoveLabelQuery {
    pub label_id: Uuid,
}
#[utoipa::path(
    post,
    path = "/api/v1/workspace/{wk}/repos/{repo}/pull-requests/{number}/labels",
    params(PrPath),
    request_body = AddPrLabel,
    responses(
        (status = 200, body = Vec<LabelResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "PR or label not found"),
    ),
    security(("session" = []))
)]
pub async fn add_label(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<PrPath>,
    params: web::Json<AddPrLabel>,
) -> Result<HttpResponse, ApiError> {
    let PrPath { wk, repo, number } = path.into_inner();
    let data = service
        .pr_add_label(&session, &wk, &repo, number, params.into_inner())
        .await?;
    ok_json(data)
}
#[utoipa::path(
    delete,
    path = "/api/v1/workspace/{wk}/repos/{repo}/pull-requests/{number}/labels",
    params(PrPath),
    responses(
        (status = 200, body = Vec<LabelResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "PR or label not found"),
    ),
    security(("session" = []))
)]
pub async fn remove_label(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<PrPath>,
    query: web::Query<RemoveLabelQuery>,
) -> Result<HttpResponse, ApiError> {
    let PrPath { wk, repo, number } = path.into_inner();
    let data = service
        .pr_remove_label(&session, &wk, &repo, number, query.label_id)
        .await?;
    ok_json(data)
}
