// stores/anjunganStore.js
// Konfigurasi anjungan — data disimpan di server SQLite via /api/config/anjungan
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useAnjunganStore = defineStore('anjungan', () => {
  const anjunganItems = ref([]);
  const isLoading = ref(false);
  const error = ref(null);

  const getAllAnjungan = computed(() => anjunganItems.value);

  const getAnjunganById = (id) => {
    return computed(() => {
      const target = Number(id);
      return anjunganItems.value.find((a) => Number(a.id) === target) || null;
    });
  };

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

  // ── CRUD via API ───────────────────────────────────────────────────────────
  const addAnjungan = async (payload) => {
    try {
      const res = await $fetch('/api/config/anjungan', { method: 'POST', body: payload });
      anjunganItems.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 updateAnjungan = async (payload) => {
    try {
      const res = await $fetch(`/api/config/anjungan/${payload.id}`, { method: 'PUT', body: payload });
      const idx = anjunganItems.value.findIndex((a) => Number(a.id) === Number(payload.id));
      if (idx !== -1) anjunganItems.value[idx] = res.data;
      return { success: true, message: res.message };
    } catch (e) {
      return { success: false, message: e.data?.message || e.message };
    }
  };

  const deleteAnjungan = async (id) => {
    try {
      const res = await $fetch(`/api/config/anjungan/${id}`, { method: 'DELETE' });
      anjunganItems.value = anjunganItems.value.filter((a) => Number(a.id) !== Number(id));
      return { success: true, message: res.message };
    } catch (e) {
      return { success: false, message: e.data?.message || e.message };
    }
  };

  return {
    anjunganItems,
    isLoading,
    error,
    getAllAnjungan,
    getAnjunganById,
    fetchAnjungan,
    addAnjungan,
    updateAnjungan,
    deleteAnjungan,
  };
}, {
  persist: false,
});
