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

export const useFirmwaresStore = defineStore("firmwares", () => {
  const firmwares = ref([]);
  const current = ref(null);
  const compatibility = ref(null);

  const listRequest = useAsyncRequest();
  const detailRequest = useAsyncRequest();
  const actionRequest = useAsyncRequest();
  const compatibilityRequest = useAsyncRequest();

  const isLoadingList = computed(() => listRequest.isLoading.value);
  const isLoadingDetail = computed(() => detailRequest.isLoading.value);
  const isUpdating = computed(() => actionRequest.isLoading.value);
  const isLoadingCompatibility = computed(() => compatibilityRequest.isLoading.value);

  async function loadFirmwares() {
    return listRequest.execute(async (signal) => {
      const result = await firmwaresApi.list({ signal });
      if (result.ok) {
        firmwares.value = result.data?.data?.firmwares || [];
      }
      return result;
    });
  }

  async function refreshFirmwares() {
    return actionRequest.execute(async () => {
      const result = await firmwaresApi.refresh();
      if (result.ok) {
        await loadFirmwares();
      }
      return result;
    });
  }

  async function loadFirmwareDetail(id) {
    return detailRequest.execute(async (signal) => {
      const result = await firmwaresApi.detail(id, { signal });
      if (result.ok) {
        current.value = result.data?.data?.firmware || null;
      }
      return result;
    });
  }

  async function loadDeviceCompatibility(deviceId) {
    return compatibilityRequest.execute(async (signal) => {
      const result = await firmwaresApi.deviceCompatibility(deviceId, { signal });
      if (result.ok) {
        compatibility.value = {
          compatible: result.data?.data?.compatible || [],
          currentVersion: result.data?.data?.current_version || "unknown",
        };
      }
      return result;
    });
  }

  async function updateDeviceFirmware(deviceId, firmwareId) {
    return actionRequest.execute(async () => {
      return firmwaresApi.updateDeviceFirmware(deviceId, firmwareId);
    });
  }

  function clearCompatibility() {
    compatibility.value = null;
  }

  return {
    firmwares,
    current,
    compatibility,
    isLoadingList,
    isLoadingDetail,
    isUpdating,
    isLoadingCompatibility,
    loadFirmwares,
    refreshFirmwares,
    loadFirmwareDetail,
    loadDeviceCompatibility,
    updateDeviceFirmware,
    clearCompatibility,
  };
});
