import { acceptHMRUpdate, defineStore } from 'pinia'
import { getDetailCode } from '/@src/service/code'

export const useCodes = defineStore('codeStore', () => {
    // 🟡 상태
    const codes = ref<Record<number, Array<{ cd: string; nm: string }>>>({})

    const loadingPromises = new Map<number, Promise<void>>()

    const setDetailCode = async (cd_grp: number) => {
        if (codes.value[cd_grp] && codes.value[cd_grp].length > 0) return

        if (loadingPromises.has(cd_grp)) {
            return loadingPromises.get(cd_grp)
        }

        const p = getDetailCode(cd_grp).then((res) => {
            codes.value[cd_grp] = res
        }).finally(() => {
            loadingPromises.delete(cd_grp)
        })

        loadingPromises.set(cd_grp, p)
        return p
    }

    // 🟢 코드 목록 가져오기
    const getCodeList = (cd_grp: number) => {
        return codes.value[cd_grp] || []
    }

    return {
        codes,
        setDetailCode,
        getCodeList,
    }
})

/**
 * Pinia supports Hot Module replacement so you can edit your stores and
 * interact with them directly in your app without reloading the page.
 *
 * @see https://pinia.esm.dev/cookbook/hot-module-replacement.html
 * @see https://vitejs.dev/guide/api-hmr.html
 */
if (import.meta.hot) {
    import.meta.hot.accept(acceptHMRUpdate(useCodes, import.meta.hot))
}
