import { ref, watch } from "vue";
import * as LaundryScanRepository from "@/repositories/LaundryScanRepository";

/**
 * Carga operadores elegibles para escanear en un área (selector en pantalla).
 */
export function useScanOperators(areaCodeRef) {
  const operators = ref([]);
  const canDelegate = ref(false);
  const loading = ref(false);

  const load = async () => {
    const code = typeof areaCodeRef === "function" ? areaCodeRef() : areaCodeRef?.value;
    if (!code) {
      operators.value = [];
      canDelegate.value = false;
      return;
    }
    loading.value = true;
    try {
      const body = await LaundryScanRepository.listOperators(code);
      operators.value = Array.isArray(body?.data) ? body.data : [];
      canDelegate.value = Boolean(body?.meta?.can_delegate);
    } catch {
      operators.value = [];
      canDelegate.value = false;
    } finally {
      loading.value = false;
    }
  };

  if (areaCodeRef && typeof areaCodeRef === "object" && "value" in areaCodeRef) {
    watch(areaCodeRef, () => load(), { immediate: false });
  }

  return { operators, canDelegate, loading, load };
}
