use axum::{
    Extension, Json,
    extract::{Path, State},
};
use serde_json::{Value, json};

use crate::{
    auth::AuthenticatedSession,
    error::ApiError,
    service::{UpdateWorkspacePayload, WorkspacePayload},
    state::AppState,
};

pub async fn list_workspaces(
    State(state): State<AppState>,
    Extension(session): Extension<AuthenticatedSession>,
) -> Result<Json<Value>, ApiError> {
    let items = state
        .service
        .list_workspaces_for_user(&session.user.id)
        .await?;
    Ok(Json(json!({ "items": items })))
}

pub async fn create_workspace(
    State(state): State<AppState>,
    Extension(session): Extension<AuthenticatedSession>,
    Json(payload): Json<WorkspacePayload>,
) -> Result<Json<Value>, ApiError> {
    let workspace = state
        .service
        .create_workspace(&session.user.id, payload)
        .await?;
    Ok(Json(json!(workspace)))
}

pub async fn get_workspace(
    Path(workspace_id): Path<String>,
    State(state): State<AppState>,
) -> Result<Json<Value>, ApiError> {
    let workspace = state
        .service
        .get_workspace(&workspace_id.as_str().into())
        .await?;
    Ok(Json(json!(workspace)))
}

pub async fn update_workspace(
    Path(workspace_id): Path<String>,
    State(state): State<AppState>,
    Json(payload): Json<UpdateWorkspacePayload>,
) -> Result<Json<Value>, ApiError> {
    let workspace = state
        .service
        .update_workspace(&workspace_id.as_str().into(), payload)
        .await?;
    Ok(Json(json!(workspace)))
}
