use crate::{ApiResponse, error::ApiError};
use actix_web::{HttpResponse, Result, web};
use service::AppService;
use service::workspace::billing::{
    WorkspaceBillingAddCreditParams, WorkspaceBillingCurrentResponse, WorkspaceBillingHistoryQuery,
    WorkspaceBillingHistoryResponse,
};
use session::Session;

#[utoipa::path(
    get,
    path = "/api/workspaces/{slug}/billing",
    params(
        ("slug" = String, Path, description = "Workspace slug")
    ),
    responses(
        (status = 200, description = "Get workspace billing info", body = ApiResponse<WorkspaceBillingCurrentResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Not a workspace member"),
        (status = 404, description = "Workspace not found"),
    ),
    tag = "Workspace"
)]
pub async fn workspace_billing_current(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<String>,
) -> Result<HttpResponse, ApiError> {
    let slug = path.into_inner();
    let resp = service.workspace_billing_current(&session, slug).await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    get,
    path = "/api/workspaces/{slug}/billing/history",
    params(
        ("slug" = String, Path, description = "Workspace slug"),
    ),
    responses(
        (status = 200, description = "Get workspace billing history", body = ApiResponse<WorkspaceBillingHistoryResponse>),
        (status = 401, description = "Unauthorized"),
    ),
    tag = "Workspace"
)]
pub async fn workspace_billing_history(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<String>,
    query: web::Query<WorkspaceBillingHistoryQuery>,
) -> Result<HttpResponse, ApiError> {
    let slug = path.into_inner();
    let resp = service
        .workspace_billing_history(&session, slug, query.into_inner())
        .await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    post,
    path = "/api/workspaces/{slug}/billing/credits",
    params(
        ("slug" = String, Path, description = "Workspace slug")
    ),
    request_body = WorkspaceBillingAddCreditParams,
    responses(
        (status = 200, description = "Add credit to workspace billing", body = ApiResponse<WorkspaceBillingCurrentResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Not a workspace member"),
    ),
    tag = "Workspace"
)]
pub async fn workspace_billing_add_credit(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<String>,
    body: web::Json<WorkspaceBillingAddCreditParams>,
) -> Result<HttpResponse, ApiError> {
    let slug = path.into_inner();
    let resp = service
        .workspace_billing_add_credit(&session, slug, body.into_inner())
        .await?;
    Ok(ApiResponse::ok(resp).to_response())
}
