/**
 * filekorolheader: 部门管理API接口 - 部门数据CRUD操作接口服务
 * 功能：API请求封装、数据转换、错误处理、部门树形管理
 * 路径：/central-config/user/department/components/departmentApi
 * 规范：遵循crop-x/docs/开发项目规范.md，使用SDK API调用，TypeScript类型安全
 */

import { getAuthToken } from "@/utils/token";
import {
  createDepartmentApiV1DepartmentsPost,
  updateDepartmentApiV1DepartmentsDepartmentIdPut,
  deleteDepartmentApiV1DepartmentsDepartmentIdDelete,
} from "@/lib/api/sdk.gen";
import {
  Department,
  CreateDepartmentForm,
} from '../types';

// 导出deleteDepartment供其他模块使用
export { deleteDepartment };

/**
 * API请求创建部门的数据结构（对应Python字段）
 */
export interface CreateDepartmentApiRequest {
  code: string;              // 部门编码
  name: string;              // 部门名称
  description?: string;      // 部门描述
  manager_name?: string;     // 管理者名称
  manager_phone?: string;    // 管理者电话
  manager_email?: string;    // 管理者邮箱（必须符合邮箱规则）
  parent_id: string;         // 父级部门ID，一级部门为空字符串
  order_index: number;       // 排序索引，0-10000的整数
  status: string;            // 状态，默认"active"表示有效
}

/**
 * API响应数据结构
 */
export interface CreateDepartmentApiResponse {
  code: string;
  name: string;
  description?: string;
  manager_name?: string;
  manager_phone?: string;
  manager_email?: string;
  parent_id: string;
  order_index: number;
  status: string;
}

/**
 * 将React表单数据（驼峰命名法）转换为API请求数据（Python蛇形命名法）
 */
export function transformCreateDepartmentData(formData: CreateDepartmentForm): CreateDepartmentApiRequest {
  return {
    code: formData.code,
    name: formData.name,
    description: formData.description || null,
    manager_name: formData.manager || undefined,
    manager_phone: formData.phone || undefined,
    manager_email: formData.email || undefined,
    parent_id: formData.parentId || "",
    order_index: formData.sort || 0,
    status: formData.status || "active",
  };
}

/**
 * 邮箱格式验证
 */
export function isValidEmail(email: string): boolean {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

/**
 * 创建部门API调用
 */
export async function createDepartment(formData: CreateDepartmentForm): Promise<CreateDepartmentApiResponse> {
  try {
    // 获取认证token
    const token = getAuthToken();
    console.log('创建部门API调用参数:', formData);

    // 转换表单数据为API请求格式
    const apiRequestData = transformCreateDepartmentData(formData);

    // 邮箱格式验证
    if (apiRequestData.manager_email && !isValidEmail(apiRequestData.manager_email)) {
      throw new Error('邮箱格式不正确');
    }

    // 使用真正的SDK API调用
    const response = await createDepartmentApiV1DepartmentsPost({
      body: apiRequestData,
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      throw new Error(`API error: ${response.error.message || 'Unknown error'}`);
    }

    const data = response.data as CreateDepartmentApiResponse;
    console.log('创建部门API响应:', data);

    return data;
  } catch (error) {
    console.error('Failed to create department:', error);
    throw error;
  }
}

/**
 * 更新部门API调用
 */
export async function updateDepartment(departmentId: string, formData: CreateDepartmentForm): Promise<CreateDepartmentApiResponse> {
  try {
    // 获取认证token
    const token = getAuthToken();
    console.log('更新部门API调用参数:', departmentId, formData);

    // 转换表单数据为API请求格式
    const apiRequestData = transformCreateDepartmentData(formData);

    // 邮箱格式验证
    if (apiRequestData.manager_email && !isValidEmail(apiRequestData.manager_email)) {
      throw new Error('邮箱格式不正确');
    }

    // 使用真正的SDK API调用
    const response = await updateDepartmentApiV1DepartmentsDepartmentIdPut({
      path: {
        department_id: departmentId,
      },
      body: apiRequestData,
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      throw new Error(`API error: ${response.error.message || 'Unknown error'}`);
    }

    const data = response.data as CreateDepartmentApiResponse;
    console.log('更新部门API响应:', data);

    return data;
  } catch (error) {
    console.error('Failed to update department:', error);
    throw error;
  }
}

/**
 * 获取默认排序索引
 */
export function getDefaultOrderIndex(): number {
  return 0;
}

/**
 * 删除部门API调用
 */
export async function deleteDepartment(departmentId: string): Promise<void> {
  try {
    // 获取认证token
    const token = getAuthToken();
    console.log('删除部门API调用参数:', departmentId);

    // 使用真正的SDK API调用
    const response = await deleteDepartmentApiV1DepartmentsDepartmentIdDelete({
      path: {
        department_id: departmentId,
      },
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      throw new Error(`API error: ${response.error.message || 'Unknown error'}`);
    }

    console.log('删除部门API响应: 成功');
  } catch (error) {
    console.error('Failed to delete department:', error);
    throw error;
  }
}

/**
 * 防抖函数
 */
export function debounce<T extends (...args: any[]) => any>(
  func: T,
  delay: number
): (...args: Parameters<T>) => void {
  let timeoutId: NodeJS.Timeout;
  return (...args: Parameters<T>) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func(...args), delay);
  };
}