//! Staff management API handlers.

use axum::{
    Json,
    extract::{Path, State},
};
use chattyness_db::{
    models::{CreateStaffRequest, StaffMember},
    queries::owner as queries,
};
use chattyness_error::AppError;
use serde::Serialize;
use sqlx::PgPool;
use uuid::Uuid;

/// Create staff response.
#[derive(Debug, Serialize)]
pub struct CreateStaffResponse {
    pub staff: StaffMember,
    pub temporary_password: Option<String>,
}

/// List all staff members.
pub async fn list_staff(State(pool): State<PgPool>) -> Result<Json<Vec<StaffMember>>, AppError> {
    let staff = queries::get_all_staff(&pool).await?;
    Ok(Json(staff))
}

/// Create a new staff member.
pub async fn create_staff(
    State(pool): State<PgPool>,
    Json(req): Json<CreateStaffRequest>,
) -> Result<Json<CreateStaffResponse>, AppError> {
    req.validate()?;

    // If user_id is provided, promote existing user
    if let Some(user_id) = req.user_id {
        let staff = queries::create_staff(&pool, user_id, req.role, None).await?;
        Ok(Json(CreateStaffResponse {
            staff,
            temporary_password: None,
        }))
    } else if let Some(ref new_user) = req.new_user {
        // Create new user and promote to staff
        let (user_id, temporary_password) = queries::create_user(&pool, new_user).await?;
        let staff = queries::create_staff(&pool, user_id, req.role, None).await?;
        Ok(Json(CreateStaffResponse {
            staff,
            temporary_password: Some(temporary_password),
        }))
    } else {
        Err(AppError::Validation(
            "Must provide either user_id or new_user".to_string(),
        ))
    }
}

/// Delete a staff member.
pub async fn delete_staff(
    State(pool): State<PgPool>,
    Path(user_id): Path<Uuid>,
) -> Result<Json<()>, AppError> {
    queries::delete_staff(&pool, user_id).await?;
    Ok(Json(()))
}
