use actix_web::{HttpResponse, web};
use serde::{Deserialize, Serialize};
use service::{
    AppService, Pagination,
    pull_request::{
        pull_request::{CreatePullRequest, UpdatePullRequest},
        types::{PullRequestFilter, PullRequestResponse},
    },
};
use session::Session;

use crate::error::ApiError;

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

fn ok() -> Result<HttpResponse, ApiError> {
    Ok(HttpResponse::Ok().finish())
}

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

#[derive(Deserialize, utoipa::IntoParams)]
pub struct PrRepoPath {
    pub wk: String,
    pub repo: String,
}
#[utoipa::path(
    post,
    path = "/api/v1/workspace/{wk}/repos/{repo}/pull-requests",
    params(
        ("wk" = String, Path, description = "Workspace name"),
        ("repo" = String, Path, description = "Repo name"),
    ),
    request_body = CreatePullRequest,
    responses(
        (status = 200, body = PullRequestResponse),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Repo not found"),
    ),
    security(("session" = []))
)]
pub async fn create_pr(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<PrRepoPath>,
    params: web::Json<CreatePullRequest>,
) -> Result<HttpResponse, ApiError> {
    let PrRepoPath { wk, repo } = path.into_inner();
    let data = service
        .pr_create(&session, &wk, &repo, params.into_inner())
        .await?;
    ok_json(data)
}
#[utoipa::path(
    get,
    path = "/api/v1/workspace/{wk}/repos/{repo}/pull-requests",
    params(
        ("wk" = String, Path, description = "Workspace name"),
        ("repo" = String, Path, description = "Repo name"),
        PullRequestFilter,
        Pagination,
    ),
    responses(
        (status = 200, body = Vec<PullRequestResponse>),
        (status = 401, description = "Unauthorized"),
    ),
    security(("session" = []))
)]
pub async fn list_prs(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<PrRepoPath>,
    filter: web::Query<PullRequestFilter>,
    pagination: web::Query<Pagination>,
) -> Result<HttpResponse, ApiError> {
    let PrRepoPath { wk, repo } = path.into_inner();
    let data = service
        .pr_list(
            &session,
            &wk,
            &repo,
            filter.into_inner(),
            pagination.into_inner(),
        )
        .await?;
    ok_json(data)
}
#[utoipa::path(
    get,
    path = "/api/v1/workspace/{wk}/repos/{repo}/pull-requests/{number}",
    params(PrPath),
    responses(
        (status = 200, body = PullRequestResponse),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "PR not found"),
    ),
    security(("session" = []))
)]
pub async fn get_pr(
    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_get(&session, &wk, &repo, number).await?;
    ok_json(data)
}
#[utoipa::path(
    patch,
    path = "/api/v1/workspace/{wk}/repos/{repo}/pull-requests/{number}",
    params(PrPath),
    request_body = UpdatePullRequest,
    responses(
        (status = 200, body = PullRequestResponse),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Only author can update"),
        (status = 404, description = "PR not found"),
    ),
    security(("session" = []))
)]
pub async fn update_pr(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<PrPath>,
    params: web::Json<UpdatePullRequest>,
) -> Result<HttpResponse, ApiError> {
    let PrPath { wk, repo, number } = path.into_inner();
    let data = service
        .pr_update(&session, &wk, &repo, number, params.into_inner())
        .await?;
    ok_json(data)
}
#[utoipa::path(
    delete,
    path = "/api/v1/workspace/{wk}/repos/{repo}/pull-requests/{number}",
    params(PrPath),
    responses(
        (status = 200, description = "PR deleted"),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Permission denied"),
        (status = 404, description = "PR not found"),
    ),
    security(("session" = []))
)]
pub async fn delete_pr(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<PrPath>,
) -> Result<HttpResponse, ApiError> {
    let PrPath { wk, repo, number } = path.into_inner();
    service.pr_delete(&session, &wk, &repo, number).await?;
    ok()
}
