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

export const useScreenStore = defineStore('screen', () => {
  const screenItems = ref([]);
  const isLoading = ref(false);
  const error = ref(null);

  const getAllScreens = computed(() => screenItems.value);

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

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

  // ── CRUD via API ───────────────────────────────────────────────────────────
  const addScreen = async (screenPayload) => {
    try {
      const res = await $fetch('/api/config/screen', { method: 'POST', body: screenPayload });
      screenItems.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 updateScreen = async (screenPayload) => {
    try {
      const res = await $fetch(`/api/config/screen/${screenPayload.id}`, { method: 'PUT', body: screenPayload });
      const index = screenItems.value.findIndex(s => s.id === screenPayload.id);
      if (index !== -1) screenItems.value[index] = res.data;
      return { success: true, message: res.message };
    } catch (e) {
      return { success: false, message: e.data?.message || e.message };
    }
  };

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

  return {
    screenItems,
    isLoading,
    error,
    getAllScreens,
    getScreenById,
    fetchScreens,
    addScreen,
    updateScreen,
    deleteScreen,
  };
}, {
  // No persist — data lives in the server DB
  persist: false,
});
