// stores/klinikruangstore.js
// Konfigurasi mapping klinik ke ruangan — data disimpan di server SQLite via /api/config/klinik-ruang
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { useClinicStore } from './clinicStore';

export const useKlinikRuangStore = defineStore('klinikRuang', () => {
  const clinicStore = useClinicStore();

  // Master klinik list (from clinicStore — in-memory, from API)
  const masterKlinikList = computed(() => {
    const baseList = typeof clinicStore.getClinicsForDropdown === 'function'
      ? clinicStore.getClinicsForDropdown()
      : [];
    return baseList.map((c) => ({ kode: c.kode, nama: c.name }));
  });

  const klinikRuangList = ref([]);
  const isLoading = ref(false);
  const error = ref(null);

  const totalKlinikRuang = computed(() => klinikRuangList.value.length);
  const totalRuangan = computed(() =>
    klinikRuangList.value.reduce((total, k) => total + (k.ruangList?.length || 0), 0)
  );

  const getKlinikByCode = (kode) => klinikRuangList.value.find(k => k.kodeKlinik === kode);
  const getRuangByKlinik = (kodeKlinik) => {
    const klinik = klinikRuangList.value.find(k => k.kodeKlinik === kodeKlinik);
    return klinik ? klinik.ruangList : [];
  };

  const searchKlinikRuang = (searchTerm) => {
    if (!searchTerm) return klinikRuangList.value;
    const term = searchTerm.toLowerCase();
    return klinikRuangList.value.filter(k =>
      k.kodeKlinik?.toLowerCase().includes(term) ||
      k.namaKlinik?.toLowerCase().includes(term)
    );
  };

  // ── Fetch from API ─────────────────────────────────────────────────────────
  const fetchKlinikRuang = async () => {
    if (isLoading.value) return;
    isLoading.value = true;
    error.value = null;
    try {
      const res = await $fetch('/api/config/klinik-ruang');
      klinikRuangList.value = (res.data || []).map((item, idx) => ({
        ...item,
        no: idx + 1,
        namaRuang: (item.ruangList || []).map(r => r.namaRuang).filter(Boolean).join(', '),
      }));
    } catch (e) {
      error.value = e.message;
      console.error('❌ [klinikRuangStore] Gagal fetch config:', e);
    } finally {
      isLoading.value = false;
    }
  };

  // ── CRUD via API ───────────────────────────────────────────────────────────
  const createKlinikRuang = async (data) => {
    try {
      const res = await $fetch('/api/config/klinik-ruang', { method: 'POST', body: data });
      const newItem = { ...res.data, no: klinikRuangList.value.length + 1, namaRuang: (res.data.ruangList || []).map(r => r.namaRuang).join(', ') };
      klinikRuangList.value.push(newItem);
      return { success: true, message: res.message, data: newItem };
    } catch (e) {
      return { success: false, message: e.data?.message || e.message };
    }
  };

  const updateKlinikRuang = async (id, data) => {
    try {
      const res = await $fetch(`/api/config/klinik-ruang/${id}`, { method: 'PUT', body: data });
      const index = klinikRuangList.value.findIndex(r => r.id === id);
      if (index !== -1) {
        klinikRuangList.value[index] = {
          ...res.data,
          no: klinikRuangList.value[index].no,
          namaRuang: (res.data.ruangList || []).map(r => r.namaRuang).join(', '),
        };
      }
      return { success: true, message: res.message, data: res.data };
    } catch (e) {
      return { success: false, message: e.data?.message || e.message };
    }
  };

  const deleteKlinikRuang = async (id) => {
    try {
      const res = await $fetch(`/api/config/klinik-ruang/${id}`, { method: 'DELETE' });
      klinikRuangList.value = klinikRuangList.value.filter(r => r.id !== id);
      // Reorder 'no'
      klinikRuangList.value.forEach((r, idx) => { r.no = idx + 1; });
      return { success: true, message: res.message };
    } catch (e) {
      return { success: false, message: e.data?.message || e.message };
    }
  };

  const addRuangToKlinik = async (klinikId, ruangData) => {
    const klinik = klinikRuangList.value.find(k => k.id === klinikId);
    if (!klinik) return { success: false, message: 'Klinik tidak ditemukan' };
    const newRuangList = [...(klinik.ruangList || []), ruangData];
    return updateKlinikRuang(klinikId, { ...klinik, ruangList: newRuangList });
  };

  const removeRuangFromKlinik = async (klinikId, ruangIndex) => {
    const klinik = klinikRuangList.value.find(k => k.id === klinikId);
    if (!klinik) return { success: false, message: 'Klinik tidak ditemukan' };
    if ((klinik.ruangList || []).length <= 1) return { success: false, message: 'Minimal harus ada 1 ruangan' };
    const newRuangList = klinik.ruangList.filter((_, i) => i !== ruangIndex);
    return updateKlinikRuang(klinikId, { ...klinik, ruangList: newRuangList });
  };

  return {
    masterKlinikList,
    klinikRuangList,
    isLoading,
    error,
    totalKlinikRuang,
    totalRuangan,
    getKlinikByCode,
    getRuangByKlinik,
    searchKlinikRuang,
    fetchKlinikRuang,
    createKlinikRuang,
    updateKlinikRuang,
    deleteKlinikRuang,
    addRuangToKlinik,
    removeRuangFromKlinik,
  };
}, {
  persist: false,
});