//! 项目 CRUD API
//!
//! 提供项目的增删改查，从 organizations 模块拆分而来。

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

use super::organizations::{NameBody, ProjectRow};
use crate::error::AppError;
use crate::middleware::auth::{self, CurrentUser};
use crate::commands::AppState;

/// GET /api/organizations/:org_id/projects — 按组织查询项目列表
pub async fn list_projects(
    user: CurrentUser,
    State(state): State<AppState>,
    Path(org_id): Path<i64>,
) -> Result<Json<Value>, AppError> {
    auth::check_permission(&user, "project:view")?;

    let db = &state.mysql;
    let rows = sqlx::query_as::<_, ProjectRow>(
        r#"SELECT id, organization_id, name FROM projects WHERE organization_id = ? ORDER BY id"#,
    )
    .bind(org_id)
    .fetch_all(db)
    .await?;

    Ok(Json(json!(rows)))
}

/// POST /api/organizations/:org_id/projects — 创建项目
pub async fn create_project(
    user: CurrentUser,
    State(state): State<AppState>,
    Path(org_id): Path<i64>,
    Json(body): Json<NameBody>,
) -> Result<Json<Value>, AppError> {
    auth::check_permission(&user, "project:create")?;

    let db = &state.mysql;
    let name = body.name.trim().to_string();
    if name.is_empty() {
        return Err(AppError::BadRequest("项目名称不能为空".into()));
    }

    let org_exists: (i64,) = sqlx::query_as(
        r#"SELECT COUNT(*) FROM organizations WHERE id = ?"#,
    )
    .bind(org_id)
    .fetch_one(db)
    .await?;

    if org_exists.0 == 0 {
        return Err(AppError::NotFound(format!("组织 {} 不存在", org_id)));
    }

    let result = sqlx::query(r#"INSERT INTO projects (organization_id, name) VALUES (?, ?)"#)
        .bind(org_id)
        .bind(&name)
        .execute(db)
        .await?;

    let id = result.last_insert_id() as i64;
    tracing::info!("创建项目 id={} name={} org_id={}", id, name, org_id);

    Ok(Json(json!({ "id": id, "organization_id": org_id, "name": name })))
}

/// PUT /api/projects/:id — 更新项目
pub async fn update_project(
    user: CurrentUser,
    State(state): State<AppState>,
    Path(id): Path<i64>,
    Json(body): Json<NameBody>,
) -> Result<Json<Value>, AppError> {
    auth::check_permission(&user, "project:edit")?;

    let db = &state.mysql;
    let name = body.name.trim().to_string();
    if name.is_empty() {
        return Err(AppError::BadRequest("项目名称不能为空".into()));
    }

    let rows = sqlx::query(r#"UPDATE projects SET name = ? WHERE id = ?"#)
        .bind(&name)
        .bind(id)
        .execute(db)
        .await?
        .rows_affected();

    if rows == 0 {
        return Err(AppError::NotFound(format!("项目 {} 不存在", id)));
    }

    tracing::info!("更新项目 id={} name={}", id, name);
    Ok(Json(json!({ "id": id, "name": name })))
}

/// DELETE /api/projects/:id — 删除项目
pub async fn delete_project(
    user: CurrentUser,
    State(state): State<AppState>,
    Path(id): Path<i64>,
) -> Result<Json<Value>, AppError> {
    auth::check_permission(&user, "project:delete")?;

    let db = &state.mysql;
    let count: (i64,) = sqlx::query_as(
        r#"SELECT COUNT(*) FROM cabinets WHERE project_id = ?"#,
    )
    .bind(id)
    .fetch_one(db)
    .await?;

    if count.0 > 0 {
        return Err(AppError::BadRequest(
            format!("项目 {} 下仍有设备，无法删除", id),
        ));
    }

    let rows = sqlx::query(r#"DELETE FROM projects WHERE id = ?"#)
        .bind(id)
        .execute(db)
        .await?
        .rows_affected();

    if rows == 0 {
        return Err(AppError::NotFound(format!("项目 {} 不存在", id)));
    }

    tracing::info!("删除项目 id={}", id);
    Ok(Json(json!({})))
}
