import { ref, computed } from "vue";
import { defineStore } from "pinia";
import { devicesApi } from "../api/modules/devices";
import { useAsyncRequest } from "../composables/useAsyncRequest";

export const useScanningStore = defineStore("scanning", () => {
  const mode = ref("setup");
  const devices = ref([]);

  const scanRequest = useAsyncRequest();

  const total = computed(() => devices.value.length);

  async function scan() {
    return scanRequest.execute(async (signal) => {
      const result =
        mode.value === "setup"
          ? await devicesApi.scanningSetup({ signal })
          : await devicesApi.scanningAll({ signal });

      if (result.ok) {
        devices.value = result.data?.data?.devices || [];
      }
      return result;
    });
  }

  function setMode(newMode) {
    mode.value = newMode;
    devices.value = [];
    scanRequest.clear();
  }

  async function setupDevice(payload) {
    return devicesApi.setupNewDevice(payload);
  }

  return {
    mode,
    devices,
    isLoading: scanRequest.isLoading,
    error: scanRequest.error,
    total,
    scan,
    setMode,
    setupDevice,
  };
});
