import { apiGet, apiPost } from "../client";
import { unifyDeviceFields } from "../mappers";

function safeId(id) {
  return encodeURIComponent(String(id));
}

function mapDevicesResponse(result) {
  if (!result.ok) {
    return result;
  }

  const devices = result.data?.data?.devices || [];

  return {
    ...result,
    data: {
      ...result.data,
      data: {
        ...result.data?.data,
        devices: devices.map(unifyDeviceFields),
      },
    },
  };
}

export const devicesApi = {
  async list() {
    return mapDevicesResponse(await apiGet("/api/v1/devices/list"));
  },

  status(id, options) {
    return apiGet(`/api/v1/devices/id/${safeId(id)}/status`, options);
  },

  reboot(id) {
    return apiGet(`/api/v1/devices/id/${safeId(id)}/reboot`);
  },

  action(payload) {
    return apiPost("/api/v1/devices/action", payload);
  },

  scanningSetup(options) {
    return apiGet("/api/v1/devices/scanning/setup", { timeoutMs: 120000, ...options });
  },

  scanningAll(options) {
    return apiGet("/api/v1/devices/scanning/all", { timeoutMs: 120000, ...options });
  },

  setupNewDevice(payload) {
    return apiPost("/api/v1/devices/setup/new-device", payload);
  },

  detail(id, options) {
    return apiGet(`/api/v1/devices/id/${safeId(id)}`, options);
  },

  updateName(id, name) {
    return apiPost("/api/v1/devices/update-name", { device_id: id, name });
  },

  updateDescription(id, description) {
    return apiPost("/api/v1/devices/update-description", { device_id: id, description });
  },

  updateAlias(id, newAlias) {
    return apiPost("/api/v1/devices/update-alias", { device_id: id, new_alias: newAlias });
  },

  remove(id) {
    return apiGet(`/api/v1/devices/id/${safeId(id)}/remove`);
  },

  resetup(id) {
    return apiPost("/api/v1/devices/resetup", { device_id: id });
  },

  reset(id) {
    return apiPost("/api/v1/devices/reset", { device_id: id });
  },

  unassign(id) {
    return apiGet(`/api/v1/devices/id/${safeId(id)}/unassign-from-area`);
  },

  placeInArea(payload) {
    return apiPost("/api/v1/devices/place-in-area", payload);
  },
};
