import { ref, watch, type Ref } from "vue";
import { useTauri, type MdmStatusData } from "./useTauri";

export interface MdmStatusState {
  data: MdmStatusData | null;
  loading: boolean;
  error: string | null;
}

export function useMdmStatus(deviceId: Ref<string | null | undefined>) {
  const { getMdmStatus, linkMdmDevice } = useTauri();

  const state = ref<MdmStatusState>({
    data: null,
    loading: false,
    error: null,
  });

  async function refresh() {
    const id = deviceId.value;
    if (!id) {
      state.value.data = null;
      return;
    }

    state.value.loading = true;
    state.value.error = null;
    try {
      state.value.data = await getMdmStatus(id);
    } catch (e: any) {
      state.value.error = e?.message ?? "MDM-Status konnte nicht geladen werden";
      state.value.data = null;
    } finally {
      state.value.loading = false;
    }
  }

  async function link(mdmId: string) {
    const id = deviceId.value;
    if (!id) return;

    state.value.loading = true;
    state.value.error = null;
    try {
      await linkMdmDevice(id, mdmId);
      await refresh();
    } catch (e: any) {
      state.value.error = e?.message ?? "MDM-Verknüpfung fehlgeschlagen";
    } finally {
      state.value.loading = false;
    }
  }

  watch(
    () => deviceId.value,
    () => refresh(),
    { immediate: true },
  );

  return {
    state,
    refresh,
    link,
  };
}
