use crate::{ApiResponse, error::ApiError};
use actix_web::{HttpResponse, Result, web};
use service::AppService;
use service::workspace::settings::WorkspaceUpdateParams;
use session::Session;

#[utoipa::path(
    patch,
    path = "/api/workspaces/{slug}",
    params(("slug" = String, Path)),
    request_body = WorkspaceUpdateParams,
    responses(
        (status = 200, description = "Update workspace", body = ApiResponse<service::workspace::info::WorkspaceInfoResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Permission denied"),
        (status = 404, description = "Workspace not found"),
        (status = 409, description = "Name already exists"),
    ),
    tag = "Workspace"
)]
pub async fn workspace_update(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<String>,
    body: web::Json<WorkspaceUpdateParams>,
) -> Result<HttpResponse, ApiError> {
    let slug = path.into_inner();
    let ws = service
        .workspace_update(&session, slug, body.into_inner())
        .await?;
    let resp = service.workspace_info(&session, ws.slug).await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    delete,
    path = "/api/workspaces/{slug}",
    params(("slug" = String, Path)),
    responses(
        (status = 200, description = "Delete workspace"),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Permission denied (owner only)"),
        (status = 404, description = "Workspace not found"),
    ),
    tag = "Workspace"
)]
pub async fn workspace_delete(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<String>,
) -> Result<HttpResponse, ApiError> {
    let slug = path.into_inner();
    service.workspace_delete(&session, slug).await?;
    Ok(ApiResponse::ok(serde_json::json!({ "success": true })).to_response())
}
