use actix_web::{HttpResponse, web};
use serde::{Deserialize, Serialize};
use service::{
    AppService, Pagination,
    git::webhook::{
        CreateWebhook, UpdateWebhook, WebhookDeliveryResponse, WebhookResponse,
    },
};
use session::Session;

use crate::error::ApiError;

use super::repo::WkRepoPath;

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 WebhookPath {
    pub wk: String,
    pub repo: String,
    pub webhook_id: uuid::Uuid,
}
#[utoipa::path(
    get,
    path = "/api/v1/workspace/{wk}/repos/{repo}/webhooks",
    params(WkRepoPath, Pagination),
    responses(
        (status = 200, body = Vec<WebhookResponse>),
        (status = 401, description = "Unauthorized"),
    ),
    security(("session" = []))
)]
pub async fn list_webhooks(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<WkRepoPath>,
    pagination: web::Query<Pagination>,
) -> Result<HttpResponse, ApiError> {
    let WkRepoPath { wk, repo } = path.into_inner();
    let data = service
        .repo_webhook_list(&session, &wk, &repo, pagination.into_inner())
        .await?;
    ok_json(data)
}
#[utoipa::path(
    post,
    path = "/api/v1/workspace/{wk}/repos/{repo}/webhooks",
    params(WkRepoPath),
    request_body = CreateWebhook,
    responses(
        (status = 200, body = WebhookResponse),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Permission denied"),
    ),
    security(("session" = []))
)]
pub async fn create_webhook(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<WkRepoPath>,
    params: web::Json<CreateWebhook>,
) -> Result<HttpResponse, ApiError> {
    let WkRepoPath { wk, repo } = path.into_inner();
    let data = service
        .repo_webhook_create(&session, &wk, &repo, params.into_inner())
        .await?;
    ok_json(data)
}
#[utoipa::path(
    put,
    path = "/api/v1/workspace/{wk}/repos/{repo}/webhooks/{webhook_id}",
    params(WebhookPath),
    request_body = UpdateWebhook,
    responses(
        (status = 200, body = WebhookResponse),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Permission denied"),
        (status = 404, description = "Webhook not found"),
    ),
    security(("session" = []))
)]
pub async fn update_webhook(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<WebhookPath>,
    params: web::Json<UpdateWebhook>,
) -> Result<HttpResponse, ApiError> {
    let WebhookPath {
        wk,
        repo,
        webhook_id,
    } = path.into_inner();
    let data = service
        .repo_webhook_update(
            &session,
            &wk,
            &repo,
            webhook_id,
            params.into_inner(),
        )
        .await?;
    ok_json(data)
}
#[utoipa::path(
    delete,
    path = "/api/v1/workspace/{wk}/repos/{repo}/webhooks/{webhook_id}",
    params(WebhookPath),
    responses(
        (status = 200, description = "Webhook deleted"),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Permission denied"),
        (status = 404, description = "Webhook not found"),
    ),
    security(("session" = []))
)]
pub async fn delete_webhook(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<WebhookPath>,
) -> Result<HttpResponse, ApiError> {
    let WebhookPath {
        wk,
        repo,
        webhook_id,
    } = path.into_inner();
    service
        .repo_webhook_delete(&session, &wk, &repo, webhook_id)
        .await?;
    ok()
}
#[utoipa::path(
    get,
    path = "/api/v1/workspace/{wk}/repos/{repo}/webhooks/{webhook_id}/deliveries",
    params(WebhookPath, Pagination),
    responses(
        (status = 200, body = Vec<WebhookDeliveryResponse>),
        (status = 401, description = "Unauthorized"),
    ),
    security(("session" = []))
)]
pub async fn list_deliveries(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<WebhookPath>,
    pagination: web::Query<Pagination>,
) -> Result<HttpResponse, ApiError> {
    let WebhookPath {
        wk,
        repo,
        webhook_id,
    } = path.into_inner();
    let data = service
        .repo_webhook_deliveries(
            &session,
            &wk,
            &repo,
            webhook_id,
            pagination.into_inner(),
        )
        .await?;
    ok_json(data)
}
