/**
 * 设备管理 API
 * 组织/项目/柜子 CRUD + 树状结构
 */
import { api } from './request';

export interface Organization {
  id: number;
  name: string;
}

export interface Project {
  id: number;
  organization_id?: number;
  name: string;
}

export interface Cabinet {
  id: number;
  project_id?: number;
  abstract_id: string;
  imei: string;
  auth_str?: string;
  name?: string;
  status: number;
}

export interface Compartment {
  id: number;
  cabin_board_id: number;
  channel_id: number;
  status: number;
}

export interface CabinBoard {
  id: number;
  board_id: number;
  status: number;
  compartments: Compartment[];
}

export interface CabinetDetail extends Cabinet {
  cabin_boards: CabinBoard[];
}

export interface TreeNode {
  id: number;
  name: string;
  children?: TreeNode[];
  abstract_id?: string;
  imei?: string;
  status?: number;
}

// 组织 API
export const orgApi = {
  list: () => api.get<Organization[]>('/organizations'),
  create: (data: { name: string }) => api.post<Organization>('/organizations', data),
  update: (id: number, data: { name: string }) => api.put(`/organizations/${id}`, data),
  delete: (id: number) => api.delete(`/organizations/${id}`),
};

// 项目 API
export const projectApi = {
  list: (orgId: number) => api.get<Project[]>(`/organizations/${orgId}/projects`),
  create: (orgId: number, data: { name: string }) =>
    api.post(`/organizations/${orgId}/projects`, data),
  update: (id: number, data: { name: string }) => api.put(`/projects/${id}`, data),
  delete: (id: number) => api.delete(`/projects/${id}`),
};

// 柜子 API
export const cabinetApi = {
  list: (projectId: number) => api.get<Cabinet[]>(`/projects/${projectId}/cabinets`),
  create: (data: { imeis: string[]; project_id: number }) =>
    api.post<{ ids: number[] }>('/cabinets', data),
  update: (id: number, data: { project_id?: number; name?: string }) =>
    api.put(`/cabinets/${id}`, data),
  delete: (id: number) => api.delete(`/cabinets/${id}`),
  regenerateAuth: (id: number) => api.post<{ auth_str: string }>(`/cabinets/${id}/regenerate-auth`),
  getDetail: (id: number) => api.get<CabinetDetail>(`/cabinets/${id}`),
};

// 组织树 API
export const treeApi = {
  get: () => api.get<TreeNode[]>('/organization-tree'),
};
