import http from '@core/http';

import type { RobotDetail, RobotGroup, RobotInfo } from './type';

const enum API {
  获取所有机器人 = '/robot/getAll',

  注册机器人 = '/robot/register',

  批量抢占控制权 = '/robot/seizeByIds',
  同步组文件 = '/robot/syncByGroupId',
}

export async function getAllRobots(): Promise<Array<RobotInfo>> {
  type D = RobotInfo[];
  try {
    const data = await http.post<D>(API.获取所有机器人);
    return data ?? [];
  } catch (error) {
    console.debug(error);
    return [];
  }
}

export async function registerRobot(robot: Omit<RobotDetail, 'id'>): Promise<RobotInfo | null> {
  type B = Omit<RobotDetail, 'id'>;
  type D = RobotInfo;
  try {
    const body = robot;
    const data = await http.post<D, B>(API.注册机器人, body);
    return data ?? null;
  } catch (error) {
    console.debug(error);
    return null;
  }
}

export async function seizeRobotByIds(ids: Array<RobotInfo['id']>): Promise<Array<RobotInfo['id']>> {
  if (!ids.length) return [];
  type B = { ids: string[] };
  type D = string[];
  try {
    const body = { ids };
    const data = await http.post<D, B>(API.批量抢占控制权, body);
    return data ?? [];
  } catch (error) {
    console.debug(error);
    return [];
  }
}
export async function syncGroupRobotsById(id: RobotGroup['id'], sid: RobotGroup['sid']): Promise<boolean> {
  if (!id || !sid) return false;
  type B = { id: string; sid: string };
  type D = void;
  try {
    const body = { id, sid };
    await http.post<D, B>(API.同步组文件, body);
    return true;
  } catch (error) {
    console.debug(error);
    return false;
  }
}
