// 类别管理模块
use serde::{Deserialize, Serialize};
use crate::database::DB_CONN;
use crate::operation_logs::log_operation;
use crate::error_util;
use crate::permissions::check_permission;
use uuid::Uuid;
use chrono::Local;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Category {
    pub id: String,
    pub name: String,
    pub parent_id: String,
    pub sort_order: i32,
    pub created_at: String,
}

#[derive(Debug, Deserialize)]
pub struct CreateCategoryRequest {
    pub name: String,
    pub parent_id: String,
    pub sort_order: i32,
}

#[tauri::command]
pub fn add_category(request: CreateCategoryRequest, username: String, real_name: String) -> Result<Category, String> {
    if !check_permission(&username, "products_edit") {
        return Err("权限不足：没有新增分类的权限".to_string());
    }
    let conn_guard = DB_CONN.lock().map_err(|e| error_util::to_chinese_error(e))?;
    let conn = conn_guard.as_ref().ok_or("系统错误：数据库未初始化")?;
    let id = Uuid::new_v4().to_string();
    let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    conn.execute("INSERT INTO categories (id, name, parent_id, sort_order, created_at) VALUES (?1,?2,?3,?4,?5)",
        [&id, &request.name, &request.parent_id, &request.sort_order.to_string(), &now]).map_err(|e| error_util::to_chinese_error(e))?;
    log_operation(&username, &real_name, "添加", "类别管理", &format!("添加类别: {}", request.name));
    Ok(Category { id, name: request.name, parent_id: request.parent_id, sort_order: request.sort_order, created_at: now })
}

#[tauri::command]
pub fn get_categories() -> Result<Vec<Category>, String> {
    let conn_guard = DB_CONN.lock().map_err(|e| error_util::to_chinese_error(e))?;
    let conn = conn_guard.as_ref().ok_or("系统错误：数据库未初始化")?;
    let mut stmt = conn.prepare("SELECT * FROM categories ORDER BY sort_order, name").map_err(|e| error_util::to_chinese_error(e))?;
    let rows = stmt.query_map([], |row| Ok(Category { id: row.get(0)?, name: row.get(1)?, parent_id: row.get::<_, Option<String>>(2)?.unwrap_or_default(), sort_order: row.get::<_, Option<i32>>(3)?.unwrap_or(0), created_at: row.get(4)? })).map_err(|e| error_util::to_chinese_error(e))?;
    rows.collect::<Result<Vec<_>, _>>().map_err(|e| error_util::to_chinese_error(e))
}

#[tauri::command]
pub fn delete_category(category_id: String, username: String, real_name: String) -> Result<String, String> {
    if !check_permission(&username, "products_edit") {
        return Err("权限不足：没有删除分类的权限".to_string());
    }
    let conn_guard = DB_CONN.lock().map_err(|e| error_util::to_chinese_error(e))?;
    let conn = conn_guard.as_ref().ok_or("系统错误：数据库未初始化")?;
    let name: String = conn.query_row("SELECT name FROM categories WHERE id=?1", [&category_id], |row| row.get(0)).unwrap_or_default();
    conn.execute("DELETE FROM categories WHERE id=?1", [&category_id]).map_err(|e| error_util::to_chinese_error(e))?;
    log_operation(&username, &real_name, "删除", "类别管理", &format!("删除类别: '{}'", name));
    Ok("删除成功".to_string())
}