// stores/antreanMasukScreenStore.js
// Konfigurasi layar antrean masuk — data disimpan di server SQLite via /api/config/antrean-masuk-screen
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useAntreanMasukScreenStore = defineStore('antreanMasukScreen', () => {
  const antreanMasukScreenItems = ref([]);
  const isLoading = ref(false);
  const error = ref(null);

  const getAllAntreanMasukScreens = computed(() => antreanMasukScreenItems.value);

  const getAntreanMasukScreenById = (id) => {
    return computed(() => {
      const targetId = Number(id);
      return antreanMasukScreenItems.value.find((s) => Number(s.id) === targetId);
    });
  };

  // ── Fetch from API ─────────────────────────────────────────────────────────
  const fetchAntreanMasukScreens = async () => {
    if (isLoading.value) return;
    isLoading.value = true;
    error.value = null;
    try {
      const res = await $fetch('/api/config/antrean-masuk-screen');
      antreanMasukScreenItems.value = res.data || [];
    } catch (e) {
      error.value = e.message;
      console.error('❌ [antreanMasukScreenStore] Gagal fetch config:', e);
    } finally {
      isLoading.value = false;
    }
  };

  // ── CRUD via API ───────────────────────────────────────────────────────────
  const addAntreanMasukScreen = async (screenPayload) => {
    try {
      const res = await $fetch('/api/config/antrean-masuk-screen', { method: 'POST', body: screenPayload });
      antreanMasukScreenItems.value.push(res.data);
      return { success: true, message: res.message, data: res.data };
    } catch (e) {
      return { success: false, message: e.data?.message || e.message };
    }
  };

  const updateAntreanMasukScreen = async (screenPayload) => {
    try {
      const res = await $fetch(`/api/config/antrean-masuk-screen/${screenPayload.id}`, { method: 'PUT', body: screenPayload });
      const index = antreanMasukScreenItems.value.findIndex(s => s.id === screenPayload.id);
      if (index !== -1) antreanMasukScreenItems.value[index] = res.data;
      return { success: true, message: res.message };
    } catch (e) {
      return { success: false, message: e.data?.message || e.message };
    }
  };

  const deleteAntreanMasukScreen = async (screenId) => {
    try {
      const res = await $fetch(`/api/config/antrean-masuk-screen/${screenId}`, { method: 'DELETE' });
      antreanMasukScreenItems.value = antreanMasukScreenItems.value.filter(s => s.id !== screenId);
      return { success: true, message: res.message };
    } catch (e) {
      return { success: false, message: e.data?.message || e.message };
    }
  };

  return {
    antreanMasukScreenItems,
    isLoading,
    error,
    getAllAntreanMasukScreens,
    getAntreanMasukScreenById,
    fetchAntreanMasukScreens,
    addAntreanMasukScreen,
    updateAntreanMasukScreen,
    deleteAntreanMasukScreen,
  };
}, {
  persist: false,
});
