/*
    작성자 : 박지윤
    작성일 : 2025-02-04
    수정자 :
    수정일 :
    설명   : 공통 api
*/
import { ref, onMounted } from "vue";
import $api from '@api';

const colorList = ref([]);
const mbtiList = ref([]);
const pwhintList = ref([]);
const yearCategory = ref([]);
const cateList = ref([]);

const refreshColorList = async (type = 'YNP') => {
    const response = await $api.get(`user/color`, {
        params: { type }
    });

    if (response.data && response.data.data) {
        colorList.value = response.data.data.map(item => ({
            label: item.CMNCODNAM,
            value: item.CMNCODVAL,
        }));
    }

    return colorList.value;
};

// CommonCode 함수를 외부에서도 접근할 수 있게 변경
const CommonCode = async (path, endpoint, targetList, type = null) => {
    const params = type ? { type } : {};
    const response = await $api.get(`${path}/${endpoint}`, {
        params
    });
    targetList.value = response.data.data.map(item => ({
        label: item.CMNCODNAM,
        value: item.CMNCODVAL,
    }));
};

const commonApi = (options = {}) => {
    onMounted(async () => {
        // 요청할 데이터가 옵션으로 전달 -> 그에 맞게 호출
        if (options.loadColor) {
            await CommonCode("user", "color", colorList, options.colorType);
        }
        if (options.loadMbti) await CommonCode("user", "mbti", mbtiList);
        if (options.loadPwhint) await CommonCode("user", "pwhint", pwhintList);
        if (options.loadYearCategory) await CommonCode("project", "yearCategory", yearCategory);
        if (options.loadCateList) await CommonCode("worddict", "getWordCategory", cateList);
    });

    return {
        colorList,
        mbtiList,
        pwhintList,
        yearCategory,
        cateList,
        refreshColorList
    };
};

export { refreshColorList };
export default commonApi;
