use actix_web::{HttpResponse, web};
use serde::{Deserialize, Serialize};
use service::{
    AppService,
    pull_request::{merge::MergePullRequest, types::PullRequestResponse},
};
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,
}
#[utoipa::path(
    get,
    path = "/api/v1/workspace/{wk}/repos/{repo}/pull-requests/{number}/merge",
    params(PrPath),
    responses(
        (status = 200, description = "Merge analysis result"),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "PR not found"),
    ),
    security(("session" = []))
)]
pub async fn merge_analysis(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<PrPath>,
) -> Result<HttpResponse, ApiError> {
    let PrPath { wk, repo, number } = path.into_inner();
    let data = service
        .pr_merge_analysis(&session, &wk, &repo, number)
        .await?;
    ok_json(data)
}
#[utoipa::path(
    post,
    path = "/api/v1/workspace/{wk}/repos/{repo}/pull-requests/{number}/merge",
    params(PrPath),
    request_body = MergePullRequest,
    responses(
        (status = 200, body = PullRequestResponse),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Permission denied"),
        (status = 404, description = "PR not found"),
    ),
    security(("session" = []))
)]
pub async fn merge_pr(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<PrPath>,
    params: web::Json<MergePullRequest>,
) -> Result<HttpResponse, ApiError> {
    let PrPath { wk, repo, number } = path.into_inner();
    let data = service
        .pr_merge(&session, &wk, &repo, number, params.into_inner())
        .await?;
    ok_json(data)
}
#[utoipa::path(
    post,
    path = "/api/v1/workspace/{wk}/repos/{repo}/pull-requests/{number}/update-branch",
    params(PrPath),
    responses(
        (status = 200, body = PullRequestResponse),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "PR not found"),
    ),
    security(("session" = []))
)]
pub async fn update_branch(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<PrPath>,
) -> Result<HttpResponse, ApiError> {
    let PrPath { wk, repo, number } = path.into_inner();
    let data = service
        .pr_update_branch(&session, &wk, &repo, number)
        .await?;
    ok_json(data)
}
